Beispiel #1
0
void MainWindow::onPlot()
{
   // Plot with gnuplot
   QTemporaryFile dataFile;
   QTemporaryFile scriptFile;

   QString date=QLocale::system().dateFormat(QLocale::ShortFormat);
   QString time="%H:%M:%S";
   date.replace("dd","%d");
   date.replace("MM","%m");
   date.replace("yy","%y");

   if (dataFile.open() && scriptFile.open()) 
   {
      dataFile.setAutoRemove(false);
      scriptFile.setAutoRemove(false);
      QTextStream out(&dataFile);
      QString data = GetDataAsCsv();
      data.replace(" ", "_");
      out << data;
      QTextStream scriptOut(&scriptFile);
      scriptOut   << "set xdata time\n"
                  << "set timefmt" << " " << "\"" << date << "_" << time <<"\"\n" 
                  << "set grid\n"
                  << "plot '" << dataFile.fileName() << "' u 1:2 title \"Temperature\" with linespoints lt 4 lw 2\n" 
                  << "pause -1\n";
      QProcess *gnuplot = new QProcess();
      QStringList arguments(scriptFile.fileName());
      arguments << "-";
      gnuplot->start("gnuplot", arguments);
      gnuplot->waitForStarted();
//    gnuplot->close();
   }
}
Beispiel #2
0
void SeqLenAnalysis::setupOnData(const TDSVector& a_data, SeqLenAnalysis& a_instance)
{
  QTemporaryFile tmpFileOut;
  QTemporaryFile tmpFileIn;
  tmpFileOut.setAutoRemove(true);
  tmpFileOut.open();
  tmpFileIn.setAutoRemove(true);
  tmpFileIn.open();
  {
    std::ofstream outputFile(tmpFileOut.fileName().toStdString().c_str());
    TDS prev = 0;
    for (auto sample: a_data) {
      outputFile << sample - prev << "\n";
      prev = sample;
    }
  }

  a_instance.ui->seqLenTable->setHorizontalHeaderItem(0, new QTableWidgetItem("value"));
  a_instance.ui->seqLenTable->setHorizontalHeaderItem(1, new QTableWidgetItem("n"));
  a_instance.ui->seqLenTable->setHorizontalHeaderItem(2, new QTableWidgetItem("mean"));
  a_instance.ui->seqLenTable->setHorizontalHeaderItem(3, new QTableWidgetItem("stddev"));
  a_instance.ui->seqLenTable->setHorizontalHeaderItem(4, new QTableWidgetItem("min"));
  a_instance.ui->seqLenTable->setHorizontalHeaderItem(5, new QTableWidgetItem("max"));

  std::cerr << (QString("../tool/bitcracker.native seqlen ") + tmpFileOut.fileName() + " >" + tmpFileIn.fileName()).toStdString().c_str() << std::endl;
  system((QString("../tool/bitcracker.native seqlen ") + tmpFileOut.fileName() + " >" + tmpFileIn.fileName()).toStdString().c_str());
  std::ifstream inputFile(tmpFileIn.fileName().toStdString().c_str());
  while (inputFile) {
    std::string str;
    if (std::getline(inputFile, str)) {
      std::stringstream st(str);
      int bit;
      int k;
      int n;
      double centroid;
      double mean;
      double stddev;
      double min;
      double max;
      st >> k >> bit >> centroid >> n >> mean;
      stddev = readNanOrDouble(st);
      st >> min >> max;
      if (0 && !st.good()) {
        std::cerr << "Failed to read\n";
      } else {
        Data d;
        d.bit = bit;
        d.n = n;
        d.mean = mean;
        d.stddev = stddev;
        d.min = min;
        d.max = max;
        a_instance.add(k, d);
      }
    }
  }
  a_instance.redraw();
}
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 #4
0
void QTestLibPlugin::projectRunHook(ProjectExplorer::Project *proj)
{
    return; //NBS TODO QTestlibplugin
    if (!proj)
        return;

    m_projectDirectory.clear();
    //NBS proj->setExtraApplicationRunArguments(QStringList());
    //NBS proj->setCustomApplicationOutputHandler(0);

    const QVariant config; //NBS  = proj->projectProperty(ProjectExplorer::Constants::P_CONFIGVAR);
    if (!config.toStringList().contains(QLatin1String("qtestlib")))
        return;

    {
        QTemporaryFile tempFile;
        tempFile.setAutoRemove(false);
        tempFile.open();
        m_outputFile = tempFile.fileName();
    }

    //NBS proj->setCustomApplicationOutputHandler(this);
    //NBS proj->setExtraApplicationRunArguments(QStringList() << QLatin1String("-xml") << QLatin1String("-o") << m_outputFile);
//    const QString proFile = proj->fileName();
//    const QFileInfo fi(proFile);
//    if (QFile::exists(fi.absolutePath()))
//        m_projectDirectory = fi.absolutePath();
}
    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"));
        }
    }
Beispiel #6
0
bool MountProtector::lock(const QString& path) {
    if (path.isEmpty()) {
        qmlInfo(this) << "Cannot lock an empty path";
        return false;
    }

    QString p = QString("%1%2.cameraplus_tmp_XXXXXX").arg(path).arg(QDir::separator());
    QTemporaryFile *file = new QTemporaryFile(p);
    file->setAutoRemove(true);

    if (!file->open()) {
        qmlInfo(this) << "Failed to lock" << file->errorString();
        delete file;
        file = 0;
        return false;
    }

    if (!QFile::remove(file->fileName())) {
        qmlInfo(this) << "Failed to remove temporarily file" << file->fileName();
    }

    m_locks.insert(path, file);

    return true;
}
Beispiel #7
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 #8
0
void ReportGenerator::convertTemplate( const QString& templ )
{
  // qDebug() << "Report BASE:\n" << templ;

  if ( ! templ.isEmpty() ) {
    QTemporaryFile temp;
    temp.setAutoRemove( false );

    if ( temp.open() ) {
      QTextStream s(&temp);

      // The following explicit coding settings were needed for Qt 4.7.3, former Qt versions
      // seemed to default on UTF-8. Try to comment the following two lines for older Qt versions
      // if needed and see if the trml file on the disk still is UTF-8 encoded.
      QTextCodec *codec = QTextCodec::codecForName("UTF-8");
      s.setCodec( codec );

      s << templ;
    } else {
      // qDebug () << "ERROR: Could not open temporar file";
    }

    // qDebug () << "Wrote rml to " << temp.fileName();

    QString dId( mDocId );

    if ( mDocId.isEmpty() ) {
      dId = ArchiveMan::self()->documentID( mArchId );
    }
    runTrml2Pdf( temp.fileName(), dId, mArchId.toString() );
  }
}
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 #10
0
/**
 * Puush upload the clipboard
 * @brief Systray::uploadClipboard
 */
void Systray::uploadClipboard()
{
    if (!isLoggedIn())
        return;

    QString text = QApplication::clipboard()->text();

    // just look for "file://" and upload it, else just upload the text itself as a text file
    if (text.isEmpty()) {
        return;
    } else if (text.contains("file://")) {
        Upload *u = new Upload(text);

        connect(u, SIGNAL(started()), this, SLOT(puushStarted()));
        connect(u, SIGNAL(finished(QString)), this, SLOT(puushDone(QString)));
    } else {
        QTemporaryFile file;
        // The file is deleted too soon before it can be uploaded since the upload is in a callback.
        // Since it's in a temporary directory it'll get deleted eventually anyways...
        file.setAutoRemove(false);

        if (file.open()) {
            file.write(text.toLocal8Bit().data());

            Upload *u = new Upload(file.fileName());

            connect(u, SIGNAL(started()), this, SLOT(puushStarted()));
            connect(u, SIGNAL(finished(QString)), this, SLOT(puushDone(QString)));
        } else {
            trayIcon->showMessage("puush-qt", tr("Error opening temporary file for writing!"),
                                  QSystemTrayIcon::Critical);
        }
    }
}
Beispiel #11
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();
    }
}
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));
            };
        };
    };
}
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 #14
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 #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 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);
}
Beispiel #17
0
bool Editor::saveFile(const QUrl &targetUrl)
{
	QUrl url(targetUrl);
	bool result = false;
	if (url.isEmpty() && currentUrl().isEmpty()) {
		result = saveFileAs();
	} else {
		if (url.isEmpty()) url = currentUrl();
		QTemporaryFile tmp;  // only used for network export
		tmp.setAutoRemove(false);
		tmp.open();
		QString filename = url.isLocalFile() ? url.toLocalFile() : tmp.fileName();
	
		QSaveFile *savefile = new QSaveFile(filename);
		if (savefile->open(QIODevice::WriteOnly)) {
			QTextStream outputStream(savefile);
			// store commands in their generic @(...) notation format, to be translatable when reopened
			// this allows sharing of scripts written in different languages
			Tokenizer tokenizer;
			tokenizer.initialize(editor->document()->toPlainText());
			const QStringList localizedLooks(Translator::instance()->allLocalizedLooks());
			QString unstranslated;
			Token* t;
			bool pendingEOL = false;  // to avoid writing a final EOL token
			while ((t = tokenizer.getToken())->type() != Token::EndOfInput) {
				if (pendingEOL) {
					unstranslated.append('\n');
					pendingEOL = false;
				}
				if (localizedLooks.contains(t->look())) {
					QString defaultLook(Translator::instance()->defaultLook(t->look()));
					unstranslated.append(QString("@(%1)").arg(defaultLook));
				} else {
					if (t->type() == Token::EndOfLine) 
						pendingEOL = true;
					else
						unstranslated.append(t->look());
				}
			}
			outputStream << KTURTLE_MAGIC_1_0 << '\n';
			outputStream << unstranslated;
			outputStream.flush();
			savefile->commit();  // check for error here?
		}
		delete savefile;
        if (!url.isLocalFile())
           {
            KIO::StoredTransferJob *job = KIO::storedPut(savefile, url, -1, 0);
                 if(job->exec()){
                    setCurrentUrl(url);
                    editor->document()->setModified(false);
                    // MainWindow will add us to the recent file list
                    emit fileSaved(url);
                    result = true; // fix GUI for saveAs and saveExamples. TODO: check 5 lines above
                }
           }
    }
	return result;
}
void KoVersionDialog::slotOpen()
{
    if (!list->currentItem())
        return;

    KoVersionInfo *version = 0;
    for (int i = 0; i < m_doc->versionList().size(); ++i) {
        if (m_doc->versionList().at(i).date.toString() == list->currentItem()->text(0)) {
            version = &m_doc->versionList()[i];
            break;
        }
    }
    if (!version)
        return;

    QTemporaryFile tmp;
    tmp.setAutoRemove(false);
    tmp.open();
    tmp.write(version->data);
    tmp.flush();
    tmp.setPermissions(QFile::ReadUser);
    tmp.flush();

    if (!m_doc->documentPart()->mainWindows().isEmpty()) { //open the version in a new window if possible
        KoDocumentEntry entry = KoDocumentEntry::queryByMimeType(m_doc->nativeOasisMimeType());
        if (entry.isEmpty()) {
            entry = KoDocumentEntry::queryByMimeType(m_doc->nativeFormatMimeType());
        }
        Q_ASSERT(!entry.isEmpty());
        QString errorMsg;
        KoPart *part= entry.createKoPart(&errorMsg);
        if (!part) {
            if (!errorMsg.isEmpty())
                KMessageBox::error(0, errorMsg);
            return;
        }
        KoMainWindow *mainWindow = part->createMainWindow();
        mainWindow ->openDocument(QUrl::fromLocalFile(tmp.fileName()));
        mainWindow ->show();
    } else {
        m_doc->openUrl(QUrl::fromUserInput(tmp.fileName()));
    }

    tmp.setAutoRemove(true);
    slotButtonClicked(Close);
}
Beispiel #19
0
void tst_QFileInfo::canonicalPath()
{
    QTemporaryFile tempFile;
    tempFile.setAutoRemove(true);
    tempFile.open();
    QFileInfo fi(tempFile.fileName());
    QCOMPARE(fi.canonicalPath(), QFileInfo(QDir::tempPath()).canonicalFilePath());
}
Beispiel #20
0
QString CSimulator::createTempFile()
{
    QTemporaryFile f;
    if (!f.open())
        return QString();

    f.setAutoRemove(false);
    return f.fileName();
}
Beispiel #21
0
static QString buildTempFile()
{
    QTemporaryFile tempFile;
    tempFile.setAutoRemove(false);
    tempFile.open();
    QString a = tempFile.fileName();
    tempFile.close();
    return a;
}
Beispiel #22
0
void
AudioEngine::onNowPlayingInfoReady( const Tomahawk::InfoSystem::InfoType type )
{
    if ( m_currentTrack.isNull() ||
         m_currentTrack->track().isNull() ||
         m_currentTrack->artist().isNull() )
        return;

    QVariantMap playInfo;

#ifndef ENABLE_HEADLESS
    QImage cover;
    cover = m_currentTrack->toQuery()->cover( QSize( 0, 0 ) ).toImage();
    if ( !cover.isNull() )
    {
        playInfo["cover"] = cover;

        QTemporaryFile* coverTempFile = new QTemporaryFile( QDir::toNativeSeparators( QDir::tempPath() + "/" + m_currentTrack->artist()->name() + "_" + m_currentTrack->album()->name() + "_tomahawk_cover.png" ) );
        if ( !coverTempFile->open() )
        {
            tDebug() << Q_FUNC_INFO << "WARNING: could not write temporary file for cover art!";
        }
        else
        {
            // Finally, save the image to the new temp file
            coverTempFile->setAutoRemove( false );
            if ( cover.save( coverTempFile, "PNG" ) )
            {
                tDebug() <<  Q_FUNC_INFO << "Saving cover image to:" << QFileInfo( *coverTempFile ).absoluteFilePath();
                playInfo["coveruri"] = QFileInfo( *coverTempFile ).absoluteFilePath();
            }
            else
                tDebug() << Q_FUNC_INFO << "failed to save cover image!";
        }
        delete coverTempFile;
    }
    else
        tDebug() << Q_FUNC_INFO << "Cover from query is null!";
#endif

    Tomahawk::InfoSystem::InfoStringHash trackInfo;
    trackInfo["title"] = m_currentTrack->track();
    trackInfo["artist"] = m_currentTrack->artist()->name();
    trackInfo["album"] = m_currentTrack->album()->name();
    trackInfo["duration"] = QString::number( m_currentTrack->duration() );
    trackInfo["albumpos"] = QString::number( m_currentTrack->albumpos() );

    playInfo["trackinfo"] = QVariant::fromValue< Tomahawk::InfoSystem::InfoStringHash >( trackInfo );
    playInfo["private"] = TomahawkSettings::instance()->privateListeningMode();

    Tomahawk::InfoSystem::InfoPushData pushData ( s_aeInfoIdentifier, type, playInfo, Tomahawk::InfoSystem::PushShortUrlFlag );

    tDebug( LOGVERBOSE ) << Q_FUNC_INFO << "pushing data with type" << type;
    Tomahawk::InfoSystem::InfoSystem::instance()->pushInfo( pushData );
}
Beispiel #23
0
void tst_QTemporaryFile::resize()
{
    QTemporaryFile file;
    file.setAutoRemove(true);
    QVERIFY(file.open());
    QVERIFY(file.resize(100));

    QCOMPARE(QFileInfo(file.fileName()).size(), qint64(100));

    file.close();
}
Beispiel #24
0
void QWpsDrawer::newTempWps() {
    QTemporaryFile tmpWps;
    tmpWps.setAutoRemove(false);
    tmpWps.setFileTemplate(QDir::tempPath()+"/XXXXXXXXXX.wps");
    if (tmpWps.open()) {
        QString tmpDir = tmpWps.fileName().left(tmpWps.fileName().length()-4);
        if (QDir::temp().mkpath(tmpDir)) {
            mTmpWpsString = tmpDir;
            DEBUGF3(QString("Created :"+mTmpWpsString).toAscii());
        }
    }
}
Beispiel #25
0
QString GetTemporaryFileName() {
  QString file;
  {
    QTemporaryFile tempfile;
    // Do not delete the file, we want to do something with it
    tempfile.setAutoRemove(false);
    tempfile.open();
    file = tempfile.fileName();
  }

  return file;
}
    // Parse!
    Node* PDFParser::parse(Parser::Context& ctx, QIODevice& stream_) const
    {
        QTemporaryFile tmp;

        // Ensure valid stream
        if (!stream_.isOpen() || !stream_.isReadable())
        {
            ctx.setErrorCode(StreamError);
            ctx.setMessage("Invalid Stream");
        }

        // Ensure not empty stream
        if (stream_.atEnd())
        {
            ctx.setErrorCode(StreamEmpty);
            ctx.setMessage("Empty Stream");
        }

        QFile * file = dynamic_cast< QFile * >(&stream_);

        // Ensure of type file
        if (file == 0)
        {
            // Save to temporary file FIXME
            tmp.open();
            tmp.write(stream_.readAll());
            tmp.close();
            tmp.open();
            file = &tmp;
            tmp.setAutoRemove(false);
        }

        QString pdfFile = file->fileName();

        Node * c_Document = UtopiaDomain.term("Document");

        Node * authority = Utopia::createAuthority();
        Node * model = Utopia::createNode(authority, c_Document);
        authority->relations(Utopia::UtopiaSystem.hasPart).append(model);

        QString fileName = pdfFile;
        model->attributes.set("papyro:pdfFile", fileName);

        Spine::DocumentHandle doc = Papyro::DocumentFactory::load(model);

        // If failed to open
        if (!doc) {
            ctx.setErrorCode(SyntaxError);
            ctx.setMessage("Unknown file format");
        }

        return authority;
    }
QStringList StoragePoolControlThread::getStoragePoolXMLDesc()
{
    QStringList result;
    QString name = args.first();
    /*
    virStoragePoolPtr *storagePool;
    unsigned int flags = VIR_CONNECT_LIST_STORAGE_POOLS_ACTIVE |
                         VIR_CONNECT_LIST_STORAGE_POOLS_INACTIVE;
    int ret = virConnectListAllStoragePools( currWorkConnect, &storagePool, flags);
    if ( ret<0 ) {
        sendConnErrors();
        free(storagePool);
        return result;
    };
    //qDebug()<<QString(virConnectGetURI(currWorkConnect));

    int i = 0;
    */
    bool read = false;
    char *Returns = NULL;
    /*
    while ( storagePool[i] != NULL ) {
        QString currNetName = QString( virStoragePoolGetName(storagePool[i]) );
        if ( !read && currNetName==name ) {
            Returns = (virStoragePoolGetXMLDesc(storagePool[i], VIR_STORAGE_XML_INACTIVE));
            if ( Returns==NULL ) sendGlobalErrors();
            else read = true;
        };
        virStoragePoolFree(storagePool[i]);
        i++;
    };
    free(storagePool);
    */
    virStoragePoolPtr storagePool = virStoragePoolLookupByName(currWorkConnect, name.toUtf8().data());
    if ( storagePool!=NULL ) {
        Returns = (virStoragePoolGetXMLDesc(storagePool, VIR_STORAGE_XML_INACTIVE));
        if ( Returns==NULL ) sendConnErrors();
        else read = true;
        virStoragePoolFree(storagePool);
    } else 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.append(f.fileName());
    f.close();
    free(Returns);
    result.append(QString("'<b>%1</b>' StoragePool %2 XML'ed").arg(name).arg((read)?"":"don't"));
    return result;
}
QString TestManager::execute(TestLevel level, LatexEditorView* edView, QCodeEdit* codeedit, QEditor* editor, BuildManager* buildManager){
	QTemporaryFile tf;
	tf.setAutoRemove(false);
	tf.open();
	QByteArray tfn = QFile::encodeName(tf.fileName());
	tf.close();
	tempResult = tfn.data();
	
	
	//codeedit, editor are passed as extra parameters and not extracted from edView, so we don't have
	//to include latexeditorview.h here
	totalTestTime = 0;
	QString tr;
	QList<QObject*> tests=QList<QObject*>()
        << new SmallUsefulFunctionsTest()
		<< new BuildManagerTest(buildManager)
		<< new CodeSnippetTest(editor)
		<< new QDocumentLineTest()
		<< new QDocumentCursorTest()
		<< new QDocumentSearchTest(editor,level==TL_ALL)
		<< new QSearchReplacePanelTest(codeedit,level==TL_ALL)
		<< new QEditorTest(editor,level==TL_ALL)
		<< new LatexEditorViewTest(edView)
		<< new LatexCompleterTest(edView)
		<< new ScriptEngineTest(edView,level==TL_ALL)
		<< new LatexEditorViewBenchmark(edView,level==TL_ALL)
		<< new StructureViewTest(edView,edView->document,level==TL_ALL)
		<< new TableManipulationTest(editor)
		<< new SyntaxCheckTest(edView)
		<< new UpdateCheckerTest(level==TL_ALL)
		<< new HelpTest();
	bool allPassed=true;
	if (level!=TL_ALL)
		tr="There are skipped tests. Please rerun with --execute-all-tests\n\n";
	for (int i=0; i <tests.size();i++){
		emit newMessage(tests[i]->metaObject()->className());
		QString res=performTest(tests[i]);
		tr+=res;
		if (!res.contains(", 0 failed, 0 skipped")) allPassed=false;
	}	
	
	tr+=QString("\nTotal testing time: %1 ms\n").arg(totalTestTime);
	
	if (!allPassed)
		tr="*** THERE SEEM TO BE FAILED TESTS! ***\n\n\n\n"+tr;
	
	QFile(QFile::decodeName(tempResult)).remove();
	
	return tr;
}
void DraggableLabel::dragPixmap()
{
	const QPixmap *currentPixmap = pixmap();

	if (currentPixmap == NULL)
		return;
	
	// Make temp file
	QTemporaryFile *tempFile = new QTemporaryFile(AppTools::addPathSeparator(QDir::tempPath()) + DRAG_LABEL_FILENAME_TEMPLATE);
	tempFile->setAutoRemove(false);

	if (!tempFile->open())
	{
		delete tempFile;
		return;
	}
	
	// Arrange data
	QMimeData *data = new QMimeData;
	data->setImageData(currentPixmap->toImage());

	// Save pixmap
	QString tempFileName = tempFile->fileName();
	currentPixmap->save(tempFileName);
	delete tempFile;

	QDEBUG("Dragged file saved to " << tempFileName);

	// Keep its name
	QList <QUrl> urls;
	urls.append(QUrl::fromLocalFile(tempFileName));
	data->setUrls(urls);

	QPixmap preview = currentPixmap->scaled(DRAG_LABEL_PREVIEW_WIDTH, DRAG_LABEL_PREVIEW_HEIGHT, Qt::KeepAspectRatio);

	QPixmap preview2(preview.width(), preview.height());
	preview2.fill(QColor(180, 180, 180));

	preview.setAlphaChannel(preview2);

	// Go drag
	QDrag *drag = new QDrag(this);

	drag->setPixmap(preview);
    drag->setMimeData(data);
	drag->setHotSpot(QPoint(preview.width() / 2, preview.height() / 2));

    // Let's go!
	drag->exec(Qt::MoveAction);
}
PRL_RESULT Stunnel::prepare(QTemporaryFile& dst_, const QByteArray data_)
{
	if (!dst_.open())
	{
		WRITE_TRACE(DBG_FATAL, "Error: cannot open a temporary file");
		return PRL_ERR_OPEN_FAILED;
	}
	dst_.setAutoRemove(true);
	if (-1 == dst_.write(data_) || !dst_.flush())
	{
		WRITE_TRACE(DBG_FATAL, "Error: cannot write to a temporary file");
		return PRL_ERR_WRITE_FAILED;
	}
	return PRL_ERR_SUCCESS;
}