コード例 #1
0
ファイル: qtemporaryfile.cpp プロジェクト: xjohncz/qt5
QTemporaryFile *QTemporaryFile::createNativeFile(QFile &file)
{
    if (QAbstractFileEngine *engine = file.d_func()->engine()) {
        if(engine->fileFlags(QAbstractFileEngine::FlagsMask) & QAbstractFileEngine::LocalDiskFlag)
            return 0; //native already
        //cache
        bool wasOpen = file.isOpen();
        qint64 old_off = 0;
        if(wasOpen)
            old_off = file.pos();
        else
            file.open(QIODevice::ReadOnly);
        //dump data
        QTemporaryFile *ret = new QTemporaryFile;
        ret->open();
        file.seek(0);
        char buffer[1024];
        while(true) {
            qint64 len = file.read(buffer, 1024);
            if(len < 1)
                break;
            ret->write(buffer, len);
        }
        ret->seek(0);
        //restore
        if(wasOpen)
            file.seek(old_off);
        else
            file.close();
        //done
        return ret;
    }
    return 0;
}
コード例 #2
0
ファイル: paymentservertests.cpp プロジェクト: Xekyo/bitcoin
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[0], 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;
}
コード例 #3
0
void SnapshotActionDialog::showSnapsotXMLDesc()
{
    if ( snapshotTree->currentIndex().isValid() ) {
        TreeItem *item = static_cast<TreeItem*>(
                snapshotTree->currentIndex().internalPointer());
        if ( nullptr!=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 ( nullptr!=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));
            };
        };
    };
}
コード例 #4
0
Result StoragePoolControlThread::getStoragePoolXMLDesc()
{
    Result result;
    QString name = task.object;
    bool read = false;
    char *Returns = NULL;
    virStoragePoolPtr storagePool = virStoragePoolLookupByName(task.sourceConn, 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.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;
}
コード例 #5
0
QgsVectorLayer* QgsRemoteDataSourceBuilder::vectorLayerFromRemoteVDS( const QDomElement& remoteVDSElem, const QString& layerName, QList<QTemporaryFile*>& filesToRemove, QList<QgsMapLayer*>& layersToRemove, bool allowCaching ) const
{
  QString providerString;
  QString formatString = remoteVDSElem.attribute( "format" );
  if ( formatString.compare( "gml", Qt::CaseInsensitive ) == 0 )
  {
    providerString = "WFS";
  }
  else
  {
    providerString = formatString;
  }

  //load file with QgsHttpTransaction
  QByteArray fileContents;
  QString uri = remoteVDSElem.text();

  QgsVectorLayer* vl = 0;

  if ( loadData( uri, fileContents ) != 0 )
  {
    return 0;
  }

  //store content into temporary file
  QTemporaryFile* tmpFile = new QTemporaryFile();
  if ( tmpFile->open() )
  {
    tmpFile->write( fileContents );
    tmpFile->flush();
  }
  else
  {
    delete tmpFile;
    return 0;
  }

  //create vector layer

  //SOS has a special datasource key...
  if ( formatString.compare( "SOS", Qt::CaseInsensitive ) == 0 )
  {
    QString url = "url=" + tmpFile->fileName() + " method=FILE xml=";
    vl =  new QgsVectorLayer( url, layerNameFromUri( tmpFile->fileName() ), providerString );
  }
  else
  {
    vl =  new QgsVectorLayer( tmpFile->fileName(), layerNameFromUri( tmpFile->fileName() ), providerString );
  }

  if ( !( vl->isValid() ) )
  {
    QgsMapServerLogger::instance()->printMessage( "vl is not valid" );
  }

  layersToRemove.push_back( vl );
  filesToRemove.push_back( tmpFile );
  return vl;
}
コード例 #6
0
void MetadataReadingWorker::process() {
    bool success = false;
    initWorker();

    QTemporaryFile argumentsFile;

    if (argumentsFile.open()) {
        LOG_INFO << "Created arguments file" << argumentsFile.fileName();

        QStringList exiftoolArguments = createArgumentsList();
        foreach (const QString &line, exiftoolArguments) {
            argumentsFile.write(line.toUtf8());
#ifdef Q_OS_WIN
            argumentsFile.write("\r\n");
#else
            argumentsFile.write("\n");
#endif
        }
コード例 #7
0
ファイル: epubdocument.cpp プロジェクト: KDE/okular
QVariant EpubDocument::loadResource(int type, const QUrl &name)
{
  int size;
  char *data;

  QString fileInPath = mCurrentSubDocument.resolved(name).path();

  // Get the data from the epub file
  size = epub_get_data(mEpub, fileInPath.toUtf8().constData(), &data);

  QVariant resource;

  if (data) {
    switch(type) {
    case QTextDocument::ImageResource:{
      QImage img = QImage::fromData((unsigned char *)data, size);
      const int maxHeight = maxContentHeight();
      const int maxWidth = maxContentWidth();
      if(img.height() > maxHeight)
        img = img.scaledToHeight(maxHeight);
      if(img.width() > maxWidth)
        img = img.scaledToWidth(maxWidth);
      resource.setValue(img);
      break;
    }
    case QTextDocument::StyleSheetResource: {
      QString css = QString::fromUtf8(data);
      checkCSS(css);
      resource.setValue(css);
      break;
    }
    case EpubDocument::MovieResource: {
      QTemporaryFile *tmp = new QTemporaryFile(QStringLiteral("%1/okrXXXXXX").arg(QDir::tempPath()),this);
      if(!tmp->open()) qCWarning(OkularEpuDebug) << "EPUB : error creating temporary video file";
      if(tmp->write(data,size) == -1) qCWarning(OkularEpuDebug) << "EPUB : error writing data" << tmp->errorString();
      tmp->flush();
      resource.setValue(tmp->fileName());
      break;
    }
    case EpubDocument::AudioResource: {
      QByteArray ba(data,size);
      resource.setValue(ba);
      break;
    }
    default:
      resource.setValue(QString::fromUtf8(data));
      break;
    }

    free(data);
  }

  // add to cache
  addResource(type, name, resource); 

  return resource;
}
コード例 #8
0
ファイル: TableLoader.cpp プロジェクト: rrnntt/plugins
/**
 * Called when data become available
 */
void TableLoader::load( const QByteArray& data)
{
  QTemporaryFile file;
  if (file.open()) {
    // file.fileName() returns the unique file name
    file.write( data );
    file.close();
    m_workspace->loadAscii( file.fileName().toStdString() );
    m_workspace->modified();
  }
}
コード例 #9
0
ファイル: GZIP.cpp プロジェクト: TurBoss/makoureactor
QByteArray GZIP::decompress(const char *data, int size, int decSize, Strategy strategy)
{
	QTemporaryFile temp;
	if(!temp.open()) {
		return QByteArray();
	}
	temp.write(data, size);
	temp.close();

	return decompress(temp.fileName(), decSize, strategy);
}
コード例 #10
0
    // 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;
    }
コード例 #11
0
ファイル: configtabappearance.cpp プロジェクト: m4r71n/CopyQ
void ConfigTabAppearance::onThemeModified(const QByteArray &bytes)
{
    QTemporaryFile tmpfile;
    if ( !openTemporaryFile(&tmpfile, ".ini") )
        return;

    tmpfile.write(bytes);
    tmpfile.flush();

    QSettings settings(tmpfile.fileName(), QSettings::IniFormat);
    loadTheme(settings);
}
コード例 #12
0
void tst_QTemporaryFile::write()
{
    QByteArray data("OLE\nOLE\nOLE");
    QTemporaryFile file;
    QVERIFY(file.open());
    QCOMPARE((int)file.write(data), data.size());
    file.reset();
    QFile compare(file.fileName());
    compare.open(QIODevice::ReadOnly);
    QCOMPARE(compare.readAll() , data);
    file.close();
}
コード例 #13
0
ファイル: iosdeploystep.cpp プロジェクト: UIKit0/qt-creator
void IosDeployStep::checkProvisioningProfile()
{
    IosDevice::ConstPtr device = iosdevice();
    if (device.isNull())
        return;

    Utils::FileName provisioningFilePath = Utils::FileName::fromString(appBundle());
    provisioningFilePath.appendPath(QLatin1String("embedded.mobileprovision"));

    // the file is a signed plist stored in DER format
    // we simply search for start and end of the plist instead of decoding the DER payload
    if (!provisioningFilePath.exists())
        return;
    QFile provisionFile(provisioningFilePath.toString());
    if (!provisionFile.open(QIODevice::ReadOnly))
        return;
    QByteArray provisionData = provisionFile.readAll();
    int start = provisionData.indexOf("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
    int end = provisionData.indexOf("</plist>");
    if (start == -1 || end == -1)
        return;
    end += 8;

    QTemporaryFile f;
    if (!f.open())
        return;
    f.write(provisionData.mid(start, end - start));
    f.flush();
    QSettings provisionPlist(f.fileName(), QSettings::NativeFormat);

    if (!provisionPlist.contains(QLatin1String("ProvisionedDevices")))
        return;
    QStringList deviceIds = provisionPlist.value(QLatin1String("ProvisionedDevices")).toStringList();
    QString targetId = device->uniqueDeviceID();
    foreach (const QString &deviceId, deviceIds) {
        if (deviceId == targetId)
            return;
    }

    m_expectFail = true;
    QString provisioningProfile = provisionPlist.value(QLatin1String("Name")).toString();
    QString provisioningUid = provisionPlist.value(QLatin1String("UUID")).toString();
    Task task(Task::Warning,
              tr("The provisioning profile \"%1\" (%2) used to sign the application "
                 "does not cover the device %3 (%4). Deployment to it will fail.")
              .arg(provisioningProfile, provisioningUid, device->displayName(),
                   targetId),
              Utils::FileName(), /* filename */
              -1, /* line */
              ProjectExplorer::Constants::TASK_CATEGORY_COMPILE);
    emit addTask(task);
}
コード例 #14
0
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;
}
コード例 #15
0
ファイル: svmpredict.cpp プロジェクト: jcan87/gaia
struct svm_model* SVMPredict::loadModel() const {
    QTemporaryFile modelFile;
    modelFile.open();
    QString filename = modelFile.fileName(); // need to keep the filename while it's open
    modelFile.write(_modelData.constData());
    modelFile.close();

    struct svm_model* model = svm_load_model(filename.toUtf8().constData());
    if (!model) {
        throw GaiaException("SVMPredict: could not load model");
    }

    return model;
}
コード例 #16
0
ファイル: rules.cpp プロジェクト: 8l/kwin
Rules::Rules(const QString& str, bool temporary)
    : temporary_state(temporary ? 2 : 0)
{
    QTemporaryFile file;
    if (file.open()) {
        QByteArray s = str.toUtf8();
        file.write(s.data(), s.length());
    }
    file.flush();
    KConfig cfg(file.fileName(), KConfig::SimpleConfig);
    readFromCfg(cfg.group(QString()));
    if (description.isEmpty())
        description = QStringLiteral("temporary");
}
コード例 #17
0
ファイル: kmimetypetest.cpp プロジェクト: KDE/kdelibs4support
// All the simple tests for findByPath are in testFindByPathUsingFileName_data.
// In here we do the tests that need some content in a temporary file.
void KMimeTypeTest::testFindByPathWithContent()
{
    KMimeType::Ptr mime;

    // Test a real PDF file.
    // If we find x-matlab because it starts with '%' then we are not ordering by priority.
    QTemporaryFile tempFile;
    QVERIFY(tempFile.open());
    QString tempFileName = tempFile.fileName();
    tempFile.write("%PDF-");
    tempFile.close();
    mime = KMimeType::findByPath(tempFileName);
    QVERIFY(mime);
    QCOMPARE(mime->name(), QString::fromLatin1("application/pdf"));
    // fast mode cannot find the mimetype
    mime = KMimeType::findByPath(tempFileName, 0, true);
    QVERIFY(mime);
    QCOMPARE(mime->name(), QString::fromLatin1("application/octet-stream"));

    // Test the case where the extension doesn't match the contents: extension wins
    {
        QTemporaryFile txtTempFile(QDir::tempPath() + QLatin1String("/kmimetypetest_XXXXXX.txt"));
        QVERIFY(txtTempFile.open());
        txtTempFile.write("%PDF-");
        QString txtTempFileName = txtTempFile.fileName();
        txtTempFile.close();
        mime = KMimeType::findByPath(txtTempFileName);
        QVERIFY(mime);
        QCOMPARE(mime->name(), QString::fromLatin1("text/plain"));
        // fast mode finds the same
        mime = KMimeType::findByPath(txtTempFileName, 0, true);
        QVERIFY(mime);
        QCOMPARE(mime->name(), QString::fromLatin1("text/plain"));
    }

    // Now the case where extension differs from contents, but contents has >80 magic rule
    // XDG spec used to say: contents wins. But we can't sniff all files...
    // XDG spec has now been amended, extensions always win.
    {
        QTemporaryFile txtTempFile(QDir::tempPath() + QLatin1String("/kmimetypetest_XXXXXX.txt"));
        QVERIFY(txtTempFile.open());
        txtTempFile.write("<smil");
        QString txtTempFileName = txtTempFile.fileName();
        txtTempFile.close();
        mime = KMimeType::findByPath(txtTempFileName);
        QVERIFY(mime);
        QCOMPARE(mime->name(), QString::fromLatin1("text/plain"));
    }
}
コード例 #18
0
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;
}
コード例 #19
0
ファイル: itemeditor.cpp プロジェクト: fade2gray/CopyQ
bool ItemEditor::start()
{
    // create temp file
    const QString tmpFileName = QString("CopyQ.XXXXXX") + getFileSuffixFromMime(m_mime);
    QString tmpPath = QDir( QDir::tempPath() ).absoluteFilePath(tmpFileName);

    QTemporaryFile tmpfile;
    tmpfile.setFileTemplate(tmpPath);
    tmpfile.setPermissions(QFile::ReadOwner | QFile::WriteOwner | QFile::ExeOwner);

    if ( !tmpfile.open() ) {
        printError( tr("Failed to open temporary file (%1) for editing item in external editor!")
             .arg(tmpfile.fileName()) );
        return false;
    }

    // write text to temp file
    tmpfile.write(m_data);
    tmpfile.flush();

    // monitor file
    m_info.setFile( tmpfile.fileName() );
    m_lastmodified = m_info.lastModified();
    m_lastSize = m_info.size();
    m_timer->start(500);
    connect( m_timer, SIGNAL(timeout()),
             this, SLOT(onTimer()) );

    // create editor process
    m_editor = new QProcess(this);
    connect( m_editor, SIGNAL(finished(int, QProcess::ExitStatus)),
            this, SLOT(close()) );
    connect( m_editor, SIGNAL(error(QProcess::ProcessError)),
            this, SLOT(onError()) );

    // use native path for filename to edit and escape all backslashes
    const QString nativeFilePath = QDir::toNativeSeparators(m_info.filePath());
    QString cmd = m_editorcmd.arg('"' + nativeFilePath + '"');
    cmd.replace("\\", "\\\\");

    // execute editor
    m_editor->start(cmd);

    tmpfile.setAutoRemove(false);
    tmpfile.close();

    return true;
}
コード例 #20
0
	void StringListRadioStation::emitPlaylist ()
	{
		QTemporaryFile file;
		file.setAutoRemove (false);
		if (!file.open ())
		{
			qWarning () << Q_FUNC_INFO
					<< "unable to open temporary file";
			return;
		}

		for (const auto& url : URLs_)
			file.write (url.toEncoded () + '\n');

		file.close ();
		emit gotPlaylist (file.fileName (), "m3u8");
	}
コード例 #21
0
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);
}
コード例 #22
0
ファイル: VstPlugin.cpp プロジェクト: karmux/lmms
void VstPlugin::loadChunk( const QByteArray & _chunk )
{
	QTemporaryFile tf;
	if( tf.open() )
	{
		tf.write( _chunk );
		tf.flush();

		lock();
		sendMessage( message( IdLoadSettingsFromFile ).
				addString(
					QSTR_TO_STDSTR(
						QDir::toNativeSeparators( tf.fileName() ) ) ).
				addInt( _chunk.size() ) );
		waitForMessage( IdLoadSettingsFromFile, true );
		unlock();
	}
}
コード例 #23
0
void TagDatabaseInMemoryTest::loadInvalidLines()
{
	QTemporaryFile file;
	QVERIFY(file.open());
	file.write("tag1,1\ntag3\n");
	file.seek(0);

	TagDatabaseInMemory database("tests/resources/tag-types.txt", file.fileName());
	QVERIFY(database.load());

	QMap<QString, TagType> types = database.getTagTypes(QStringList() << "tag1" << "tag3");

	QCOMPARE(types.count(), 1);
	QCOMPARE(types.contains("tag1"), true);
	QCOMPARE(types.contains("tag3"), false);
	QCOMPARE(types.value("tag1").name(), QString("artist"));
	QCOMPARE(database.count(), 1);
}
コード例 #24
0
void CMakeParserTest::testParserWithBadData()
{
    QFETCH( QString, text );
    QTemporaryFile tempFile;
    tempFile.setAutoRemove( false );
    tempFile.open();
    if ( !QFile::exists( tempFile.fileName() ) )
        QFAIL( "Unable to open temporary file" );

    tempFile.write( text.toUtf8() );
    QString tempName = tempFile.fileName();
    tempFile.close(); //hacks to the get name of the file
//    CMakeAst* ast = new CMakeAst;
//    bool parseError = CMakeListsParser::parseCMakeFile( ast, qPrintable( tempName ) );
//    delete ast;
//    QVERIFY( parseError == true );
    tempFile.remove();
}
コード例 #25
0
ファイル: main.cpp プロジェクト: MarianMMX/MarianMMX
void tst_qtemporaryfile::readwrite()
{
    QFETCH(qint64, amount);

    const int dataSize = 4096;
    QByteArray data;
    data.fill('a', dataSize);
    QBENCHMARK {
        for (qint64 i = 0; i < amount; ++i) {
            QTemporaryFile file;
            file.open();
            file.write(data);
            file.seek(0);
            file.read(dataSize);
            file.close();
        }
    }
}
コード例 #26
0
void tst_QTemporaryFile::size()
{
    QTemporaryFile file;
    QVERIFY(file.open());
    QVERIFY(file.exists());
    QVERIFY(!file.isSequential());
    QByteArray str("foobar");
    file.write(str);
    QVERIFY(QFile::exists(file.fileName()));
    // On CE it takes more time for the filesystem to update
    // the information. Usually you have to close it or seek
    // to get latest information. flush() does not help either.
#if !defined(Q_OS_WINCE)
    QCOMPARE(file.size(), qint64(6));
#endif
    file.seek(0);
    QCOMPARE(file.size(), qint64(6));
}
コード例 #27
0
ファイル: itemeditor.cpp プロジェクト: m4r71n/CopyQ
bool ItemEditor::start()
{
    // create temp file
    QTemporaryFile tmpfile;
    const auto suffix = getFileSuffixFromMime(m_mime);
    if ( !openTemporaryFile(&tmpfile, suffix) ) {
        log("Failed to create temporary file for external editor", LogError);
        return false;
    }

    const auto fileName = tmpfile.fileName();

    // write text to temp file
    tmpfile.write(m_data);

    // Close file before launching editor (this is required on Windows).
    tmpfile.setAutoRemove(false);
    tmpfile.close();

    // monitor file
    m_info.setFile(fileName);
    m_lastmodified = m_info.lastModified();
    m_lastSize = m_info.size();
    m_timer->start(500);
    connect( m_timer, &QTimer::timeout,
             this, &ItemEditor::onTimer );

    // create editor process
    m_editor = new QProcess(this);
    connectProcessFinished(m_editor, this, &ItemEditor::close);
    connectProcessError(m_editor, this, &ItemEditor::onError);

    // use native path for filename to edit
    const auto nativeFilePath = QDir::toNativeSeparators( m_info.absoluteFilePath() );
    const auto cmd = m_editorcmd.arg('"' + nativeFilePath + '"');

    // execute editor
    m_editor->start(cmd, QIODevice::ReadOnly);
    m_editor->closeWriteChannel();
    m_editor->closeReadChannel(QProcess::StandardOutput);

    return m_editor->waitForStarted(10000);
}
コード例 #28
0
void TagDatabaseInMemoryTest::loadValidData()
{
	QTemporaryFile file;
	QVERIFY(file.open());
	file.write("tag1,0\ntag2,1\ntag3,3\ntag4,4");
	file.seek(0);

	TagDatabaseInMemory database("tests/resources/tag-types.txt", file.fileName());
	QVERIFY(database.load());

	QMap<QString, TagType> types = database.getTagTypes(QStringList() << "tag1" << "tag3");

	QCOMPARE(types.count(), 2);
	QCOMPARE(types.contains("tag1"), true);
	QCOMPARE(types.contains("tag3"), true);
	QCOMPARE(types.value("tag1").name(), QString("general"));
	QCOMPARE(types.value("tag3").name(), QString("copyright"));
	QCOMPARE(database.count(), 4);
}
コード例 #29
0
ファイル: qeditor_t.cpp プロジェクト: svn2github/texstudio
//checks if load/saving preserves encoding and line endings
void QEditorTest::loadSave(){
	QFETCH(QString, outCodecName);
	QFETCH(QString, outLineEnding);
	QFETCH(bool, autodetect);
	QTextCodec* outCodec=QTextCodec::codecForName(qPrintable(outCodecName));
	if (outCodecName=="latin1") outCodec = defaultCodec;

	if (!allTests) {
		qDebug("skipped load save test");
		return;
	}

	const QString testText = QString::fromLatin1("hallo\n\xE4\xF6\xFC\n");
	QString testTextWithLineEndings=testText;
	testTextWithLineEndings.replace("\n",outLineEnding);
	QTemporaryFile tf;//uncomment if you need to look at the files &tf=*(new QTemporaryFile);
	tf.open();
	QString tfn=tf.fileName();
	tf.write(outCodec->fromUnicode(testTextWithLineEndings));
	tf.close();

	//Load
	editor->setFileCodec(QTextCodec::codecForName("iso-8859-5"));
	editor->load(tfn,autodetect?0:outCodec);
	editor->document()->setLineEnding(editor->document()->originalLineEnding()); //TODO: find out why this line is only needed iff the editor passed by the testmanager is used and not if a new QEditor(0) is created
	QEQUAL2(editor->document()->text(),testTextWithLineEndings,QString("File: %1  Got file codec: %2 ").arg(tfn).arg(editor->getFileCodec()?QString::fromAscii(editor->getFileCodec()->name()):"<null>"));
	QVERIFY2(editor->getFileCodec()==outCodec,qPrintable(QString("wrong encoding: got %1 wanted %2 by the sheriff %3").arg(QString::fromAscii(editor->getFileCodec()->name())).arg(QString::fromAscii(outCodec->name())).arg(autodetect)));
	QEQUAL(editor->document()->lineEndingString(),outLineEnding);

	//Save
	editor->setText(editor->document()->text()+"Save test", false);
	editor->save();
	tf.open();
	QString writtenText=outCodec->toUnicode( tf.readAll());
	tf.close();

	QEQUAL2(writtenText, testTextWithLineEndings+"Save test", "file text check, file:"+tfn);
	QVERIFY2(writtenText.contains(outLineEnding), qPrintable("file don't contain right line ending, file"+tfn));
	
	editor->setFileName(""); //reset filename so it won't get panically if the file is deleted
	editor->document()->setLineEnding(QDocument::Conservative); //reset line ending so we won't screw up the other tests
}
コード例 #30
0
ファイル: settingsdialog.cpp プロジェクト: FengJianjian/zeal
// creates a total download progress for multiple QNetworkReplies
void SettingsDialog::downloadProgress(qint64 received, qint64 total)
{
    // Don't show progress for non-docset pages
    if (total == -1 || received < 10240)
        return;

    QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender());
    if (!reply || !reply->isOpen())
        return;

    if (reply->property(DownloadTypeProperty).toInt() == DownloadDocset)  {
        const QString docsetName = reply->property(DocsetNameProperty).toString();

        QTemporaryFile *tmpFile = m_tmpFiles[docsetName];
        if (!tmpFile) {
            tmpFile = new QTemporaryFile(this);
            tmpFile->open();
            m_tmpFiles.insert(docsetName, tmpFile);
        }

        tmpFile->write(reply->read(received));
    }

    // Try to get the item associated to the request
    QListWidgetItem *item
            = ui->availableDocsetList->item(reply->property(ListItemIndexProperty).toInt());
    if (item)
        item->setData(ProgressItemDelegate::ValueRole, percent(received, total));

    qint64 previousReceived = 0;
    const QVariant previousReceivedVariant = reply->property(DownloadPreviousReceived);
    if (!previousReceivedVariant.isValid())
        m_combinedTotal += total;
    else
        previousReceived = previousReceivedVariant.toLongLong();

    m_combinedReceived += received - previousReceived;
    reply->setProperty(DownloadPreviousReceived, received);

    displayProgress();
}