当前位置: 首页>>代码示例>>C++>>正文


C++ QTemporaryFile类代码示例

本文整理汇总了C++中QTemporaryFile的典型用法代码示例。如果您正苦于以下问题:C++ QTemporaryFile类的具体用法?C++ QTemporaryFile怎么用?C++ QTemporaryFile使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了QTemporaryFile类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: autofix

void autofix(QString originalFileName, int numFiles, QSize size)
{
    std::cout << "Autofixing " << numFiles << size.width() << "x" << size.height()
              << " thumbnails of " << originalFileName.toLocal8Bit().constData() << "\n";

    QEventLoop loop;
    QTime time;

    Quill::setTemporaryFilePath(QDir::homePath() + Strings::testsTempDir);
    Quill::setPreviewSize(0, size);

    QString fileName[numFiles];
    QuillFile *quillFile[numFiles];

    for (int i=0; i<numFiles; i++) {
        {   // Needed for the life of the QTemporaryFile
            QTemporaryFile file;
            file.setFileTemplate(QDir::homePath() + Strings::testsTempFilePattern);
            file.open();
            fileName[i] = file.fileName();
            file.close();
        }
        QFile::remove(fileName[i]);
        QFile::copy(originalFileName, fileName[i]);
    }

    time.start();

    for (int i=0; i<numFiles; i++) {
        quillFile[i] = new QuillFile(fileName[i], Strings::jpegMimeType);
        QObject::connect(quillFile[i], SIGNAL(imageAvailable(const QuillImageList)),
                         &loop, SLOT(quit()));
    }

    int initTime = time.elapsed();

    for (int i=0; i<numFiles; i++)
        quillFile[i]->setDisplayLevel(0);

    int displayLevelTime = time.elapsed();

    do
        loop.exec();
    while (Quill::isCalculationInProgress());

    int prepareTime = time.elapsed();

    for (int i=0; i<numFiles; i++)
        if (quillFile[i]->image(0).isNull()) {
            std::cout<<"Error: not all images are loaded!\n";
            return;
        }

    time.restart();

    for (int i=0; i<numFiles; i++) {
        QuillImageFilter *filter =
            QuillImageFilterFactory::createImageFilter(QuillImageFilter::Name_AutoLevels);
        quillFile[i]->runFilter(filter);
    }

    do
        loop.exec();
    while (Quill::isCalculationInProgress());

    int finalTime = time.elapsed();

    for (int i=0; i<numFiles; i++)
        if (quillFile[i]->image(0).isNull()) {
            std::cout<<"Error: not all images are edited!\n";
            return;
        }

    std::cout << "Initialize " << numFiles << " QuillFiles: "
             << initTime << "ms" << "\n";

    std::cout << "Set display levels of " << numFiles << " QuillFiles: "
             << displayLevelTime - initTime << "ms" << "\n";

    std::cout << "Total prepare " << numFiles << " QuillFiles: "
             << prepareTime << "ms" << "\n";

    std::cout << "Use case edit response for " << numFiles << " QuillFiles: "
             << finalTime << "ms" << "\n";

    for (int i=0; i<numFiles; i++) {
        delete quillFile[i];
        QFile::remove(fileName[i]);
    }
}
开发者ID:alinelena,项目名称:quill,代码行数:90,代码来源:autofix.cpp

示例2: testSessionUndoRedo

void ut_stack::testSessionUndoRedo()
{
    QTemporaryFile testFile;
    testFile.open();

    QuillImage image = Unittests::generatePaletteImage();
    image.save(testFile.fileName(), "png");

    QuillImageFilter *filter =
        QuillImageFilterFactory::createImageFilter(QuillImageFilter::Name_BrightnessContrast);
    QVERIFY(filter);
    filter->setOption(QuillImageFilter::Brightness, QVariant(20));
    QuillImage resultImage = filter->apply(image);

    QuillImageFilter *filter2 =
        QuillImageFilterFactory::createImageFilter(QuillImageFilter::Name_BrightnessContrast);
    QVERIFY(filter);
    filter2->setOption(QuillImageFilter::Contrast, QVariant(20));
    QuillImage resultImage2 = filter2->apply(resultImage);

    QuillImageFilter *filter3 =
        QuillImageFilterFactory::createImageFilter(QuillImageFilter::Name_Flip);
    QVERIFY(filter);
    QuillImage resultImage3 = filter3->apply(resultImage2);

    QuillImageFilter *filter4 =
        QuillImageFilterFactory::createImageFilter(QuillImageFilter::Name_Rotate);
    QVERIFY(filter);
    filter4->setOption(QuillImageFilter::Angle, QVariant(90));
    QuillImage resultImage4 = filter4->apply(resultImage3);

    Quill::setEditHistoryCacheSize(0, 5);
    QuillFile *file = new QuillFile(testFile.fileName(), Strings::png);

    file->runFilter(filter);

    file->startSession();
    file->runFilter(filter2);

    // Inside a session, we should be able to undo
    QVERIFY(file->canUndo());
    QVERIFY(!file->canRedo());

    file->runFilter(filter3);
    file->endSession();

    // Should still be able to undo
    QVERIFY(file->canUndo());

    file->runFilter(filter4);

    // Get up to date
    file->setDisplayLevel(0);
    Quill::releaseAndWait();
    Quill::releaseAndWait();
    Quill::releaseAndWait();
    Quill::releaseAndWait();
    Quill::releaseAndWait();

    QVERIFY(Unittests::compareImage(file->image(), resultImage4));

    // Undo - single command

    file->undo();
    QVERIFY(Unittests::compareImage(file->image(), resultImage3));

    // Undo - session command

    file->undo();
    QVERIFY(Unittests::compareImage(file->image(), resultImage));

    QVERIFY(file->canUndo());
    QVERIFY(file->canRedo());

    // Redo - session command

    file->redo();
    QVERIFY(Unittests::compareImage(file->image(), resultImage3));

    delete file;
}
开发者ID:alinelena,项目名称:quill,代码行数:81,代码来源:ut_stack.cpp

示例3: NS_ENSURE_ARG_POINTER

NS_IMETHODIMP nsDeviceContextSpecQt::GetSurfaceForPrinter(
        gfxASurface** aSurface)
{
    NS_ENSURE_ARG_POINTER(aSurface);
    *aSurface = nullptr;

    double width, height;
    mPrintSettings->GetEffectivePageSize(&width, &height);

    // If we're in landscape mode, we'll be rotating the output --
    // need to swap width & height.
    int32_t orientation;
    mPrintSettings->GetOrientation(&orientation);
    if (nsIPrintSettings::kLandscapeOrientation == orientation) {
        double tmp = width;
        width = height;
        height = tmp;
    }

    // convert twips to points
    width  /= TWIPS_PER_POINT_FLOAT;
    height /= TWIPS_PER_POINT_FLOAT;

    DO_PR_DEBUG_LOG(("\"%s\", %f, %f\n", mPath, width, height));

    QTemporaryFile file;
    if(!file.open()) {
        return NS_ERROR_GFX_PRINTER_COULD_NOT_OPEN_FILE;
    }
    file.setAutoRemove(false);

    nsresult rv = NS_NewNativeLocalFile(
            nsDependentCString(file.fileName().toUtf8().constData()),
            false,
            getter_AddRefs(mSpoolFile));
    if (NS_FAILED(rv)) {
        file.remove();
        return NS_ERROR_GFX_PRINTER_COULD_NOT_OPEN_FILE;
    }

    mSpoolName = file.fileName().toUtf8().constData();

    mSpoolFile->SetPermissions(0600);

    nsCOMPtr<nsIFileOutputStream> stream =
        do_CreateInstance("@mozilla.org/network/file-output-stream;1");

    rv = stream->Init(mSpoolFile, -1, -1, 0);
    if (NS_FAILED(rv))
        return rv;

    int16_t format;
    mPrintSettings->GetOutputFormat(&format);

    nsRefPtr<gfxASurface> surface;
    gfxSize surfaceSize(width, height);

    if (format == nsIPrintSettings::kOutputFormatNative) {
        if (mIsPPreview) {
            // There is nothing to detect on Print Preview, use PS.
            // TODO: implement for Qt?
            //format = nsIPrintSettings::kOutputFormatPS;
            return NS_ERROR_NOT_IMPLEMENTED;
        }
        format = nsIPrintSettings::kOutputFormatPDF;
    }
    if (format == nsIPrintSettings::kOutputFormatPDF) {
        surface = new gfxPDFSurface(stream, surfaceSize);
    } else {
        return NS_ERROR_NOT_IMPLEMENTED;
    }

    NS_ABORT_IF_FALSE(surface, "valid address expected");

    surface.swap(*aSurface);
    return NS_OK;
}
开发者ID:,项目名称:,代码行数:77,代码来源:

示例4: QSettings

// ---------------------------------------------------------------------
// reads and updates qtide.cfg file
void Config::initide()
{
  QString f=ConfigPath.filePath("qtide.cfg");
  QSettings *s=new QSettings(f,QSettings::IniFormat);
  QString h,t,w;

  QString font="Monospace";
  int fontsize=10;
  QFont::Weight fontweight=QFont::Normal;

  QString terminal="gnome-terminal";

#ifdef __MACH__
  font="Menlo";
  fontsize=14;
  terminal="/Applications/Utilities/Terminal.app/Contents/MacOS/Terminal";
#endif
#ifdef _WIN32
  font="Lucida Console";
  terminal="cmd.exe";
#endif

#ifdef TABCOMPLETION
  Completion = s->value("Session/Completion",false).toBool();
  CompletionFile = s->value("Session/CompletionFile","stdlib.txt").toString();
#endif
  BoxForm = s->value("Session/BoxForm",0).toInt();
  ConfirmClose = s->value("Session/ConfirmClose",false).toBool();
  ConfirmSave = s->value("Session/ConfirmSave",false).toBool();
  EscClose = s->value("Session/EscClose",false).toBool();
  Font.setFamily(s->value("Session/FontFamily",font).toString());
  Font.setPointSize(s->value("Session/FontSize",fontsize).toInt());

  w=s->value("Session/FontWeight","normal").toString().toLower();
  if (w=="bold") fontweight=QFont::Bold;
  Font.setWeight(fontweight);

  KeepCursorPosOnRecall = s->value("Session/KeepCursorPosOnRecall",false).toBool();
  LineNos = s->value("Session/LineNumbers",false).toBool();

  int len=s->value("Session/MaxInputLog",-1).toInt();
  if (len<0)
    len=(s->value("Session/KeepInputLog",true).toBool()) ? 100 : 0;
  MaxInputLog=len;

  MaxRecent = s->value("Session/MaxRecent",15).toInt();
  OpenTabAt=s->value("Session/OpenTabAt",0).toInt();
  Snapshots = s->value("Session/Snapshots",true).toInt();
  Snapshotx = s->value("Session/Snapshotx","").toString();
  TermSyntaxHighlight = s->value("Session/TermSyntaxHighlight",false).toBool();
  TrimTrailingWS = s->value("Session/TrimTrailingWS",false).toBool();

  QStringList fx;
  fx = s->value("FindinFiles/Extensions","").toStringList();
  fx=qsltrimeach(fx);
  fx.removeAll("");
  if (fx.isEmpty())
    fx << "ijs ijt" << "c cfg cpp h ijs ijt jproj js sh txt" << "htm html" << "*";
  FifExt=fx;

  Terminal = s->value("Run/Terminal",terminal).toString();

  t = s->value("Position/Debug","-590 50 540 500").toString();
  DebugPos=q2p(t);
  DebugPosX=initposX(DebugPos);

  t = s->value("Position/Edit","600 100 750 750").toString();
  EditPos=q2p(t);
  EditPosX=initposX(EditPos);

  t = s->value("Position/Term","0 0 500 600").toString();
  TermPos=q2p(t);
  TermPosX=initposX(TermPos);

  if (s->allKeys().contains("Session/LineNumbers")) return;

  delete s;
  w=(fontweight==QFont::Normal) ? "normal" : "bold";
#ifdef _WIN32
  QFile temp(ConfigPath.filePath("qtide.cfg.0"));
#else
  QTemporaryFile temp;
  temp.open();
  temp.close();
#endif
  s=new QSettings(temp.fileName(),QSettings::IniFormat);
#ifdef TABCOMPLETION
  s->setValue("Session/Completion",Completion);
  s->setValue("Session/CompletionFile",CompletionFile);
#endif
  s->setValue("Session/BoxForm",BoxForm);
  s->setValue("Session/ConfirmClose",ConfirmClose);
  s->setValue("Session/ConfirmSave",ConfirmSave);
  s->setValue("Session/EscClose",EscClose);
  s->setValue("Session/FontFamily",Font.family());
  s->setValue("Session/FontSize",Font.pointSize());
  s->setValue("Session/FontWeight",w);
  s->setValue("Session/KeepCursorPosOnRecall",KeepCursorPosOnRecall);
//.........这里部分代码省略.........
开发者ID:,项目名称:,代码行数:101,代码来源:

示例5: getDevice

void CDeviceGarmin::uploadMap(const QList<IMapSelection*>& mss)
{
    Garmin::IDevice * dev = getDevice();
    if(dev == 0) return;

    QList<IMapSelection*>::const_iterator ms = mss.begin();

    while(ms != mss.end())
    {
        if((*ms)->type == IMapSelection::eVector)
        {
            break;
        }
        ++ms;
    }
    if(ms == mss.end()) return;

    CMapSelectionGarmin * gms = (CMapSelectionGarmin*)(*ms);
    QTemporaryFile tmpfile;
    tmpfile.open();

    CGarminExport dlg(0);
    dlg.exportToFile(*gms, tmpfile.fileName());
    if(dlg.hadErrors())
    {
        QMessageBox::warning(0,tr("Error..."), tr("Failed to create image file."),QMessageBox::Abort,QMessageBox::Abort);
        return;
    }

    QStringList keys;
    QMap<QString, CMapSelectionGarmin::map_t>::const_iterator map = gms->maps.begin();
    while(map != gms->maps.end())
    {
        if(!map->unlockKey.isEmpty())
        {
            keys << map->unlockKey;
        }
        ++map;
    }

    QFileInfo fi(tmpfile.fileName());

    qDebug() << fi.size();
    QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
    try
    {
        dev->uploadMap(tmpfile.fileName().toLocal8Bit(), (quint32)fi.size() , keys.isEmpty() ? 0 : keys[0].toLatin1().data());
        if (CResources::self().playSound())
        {
            QSound::play(":/sounds/xfer-done.wav");
        }
        QApplication::restoreOverrideCursor();
    }
    catch(int)
    {
        QMessageBox::warning(0,tr("Device Link Error"),dev->getLastError().c_str(),QMessageBox::Ok,QMessageBox::NoButton);
        QApplication::restoreOverrideCursor();
        return;
    }

    theMainWindow->getCanvas()->setFadingMessage(tr("Upload maps finished!"));
}
开发者ID:Nikoli,项目名称:qlandkartegt,代码行数:62,代码来源:CDeviceGarmin.cpp

示例6: QStringList

// Convienence function to send notifications.  This function does some processing
// of the arguments.  In these functions:
//    expire_timeout: The amount of time in milliseconds the message is shown.
//                    A value of -1 means timeout is based on server's settings.
//    overwrite     : Will overwrite the previous message sent from this function.
//                    It will not overwrite notifications sent by other programs. 
//
//
// Show notification with summary, app_name, and body text
void NotifyClient::sendNotification ()
{
  // make sure we have a connection we can send the notification to.
  if (! b_validconnection) return;  
  
  // variables
  QString app_name = s_app_name;  
  quint32 replaces_id = 0;
  QString app_icon = "";
  QString body = ""; 
  QString summary = s_summary;
  QStringList actions = QStringList();
  QVariantMap hints;
  int expire_timeout = i_expire_timeout;
  
  // set replaces_id
  if (b_overwrite) replaces_id = current_id;
  
  // assemble the hints
  hints.clear();
  hints.insert("urgency", QVariant::fromValue(static_cast<uchar>(i_urgency)) );
  //if (! app_icon.isEmpty() ) hints.insert("image-path", QVariant::fromValue(app_icon));
  
  // make sure we can display the text on this server
  if (sl_capabilities.contains("body", Qt::CaseInsensitive) ) {
    body = s_body;
    if (! sl_capabilities.contains ("body-markup", Qt::CaseInsensitive) ) {
      QTextDocument td;
      td.setHtml(body);
      body = td.toPlainText();
    } // if server cannot display markup
  } // if capabilities contains body
  
  // process the icon, if we are using a fallback icon create a temporary file to hold it
    QTemporaryFile*  tempfileicon = NULL; 
    if (! s_icon.isEmpty() ) {   
			if (QFile::exists(s_icon) ) {
				tempfileicon = new QTemporaryFile(this);
				tempfileicon->setAutoRemove(false);
				if (tempfileicon->open() ) {
					QPixmap px = QPixmap(s_icon);
					px.save(tempfileicon->fileName(),"PNG");
					app_icon =  tempfileicon->fileName().prepend("file://");
				} // if tempfileicon could be opened
			} // if s_icon exists as a disk file

			// assume s_icon exists as a theme icon, don't check it here.  That
			// check needs to be done in the calling program.
			else app_icon = s_icon;
		} // if s_icon is not empty
    
  QDBusReply<quint32> reply = notifyclient->call(QLatin1String("Notify"), app_name, replaces_id, app_icon, summary, body, actions, hints, expire_timeout);
  
  if (reply.isValid() ) {
		current_id = reply.value();
    if (file_map.contains(current_id) && tempfileicon != NULL) {
			if (b_overwrite) {
				file_map.value(current_id)->remove();
				delete file_map.value(current_id);
				file_map.remove(current_id);				
			}	// if
			else {
				tempfileicon->remove();
				delete tempfileicon;
				tempfileicon = NULL;
			}	// else
		}	// if contains current_id and not NULL
		if (tempfileicon != NULL) file_map[current_id] = tempfileicon;
  }	// if reply is valid
  
  else
	#if QT_VERSION >= 0x050400 
		qCritical("CMST - Error reply received to the Notify method: %s", qUtf8Printable(reply.error().message()) );
  #else
    qCritical("CMST - Error reply received to the Notify method: %s", qPrintable(reply.error().message()) );
  #endif
  
  return;
} 
开发者ID:andrew-bibb,项目名称:cmst,代码行数:88,代码来源:notify.cpp

示例7: redeye

void redeye(QString originalFileName, int numFiles, QSize size, QPoint center, int radius)
{
    std::cout << "Removing red eyes from " << numFiles << size.width() << "x" << size.height()
              << " thumbnails of " << originalFileName.toLocal8Bit().constData() << " at point "
              << center.x() << "x" << center.y()
              << " with tolerance " << radius << "\n";

    QEventLoop loop;
    QTime time;

    Quill::setTemporaryFilePath(QDir::homePath() + Strings::testsTempDir);
    Quill::setPreviewSize(0, size);

    QString fileName[numFiles];
    QuillFile *quillFile[numFiles];

    for (int i=0; i<numFiles; i++) {
        {   // Needed for the life of the QTemporaryFile
            QTemporaryFile file;
            file.setFileTemplate(QDir::homePath() + Strings::testsTempFilePattern);
            file.open();
            fileName[i] = file.fileName();
            file.close();
        }
        QFile::remove(fileName[i]);
        QFile::copy(originalFileName, fileName[i]);
    }

    time.start();

    for (int i=0; i<numFiles; i++) {
        quillFile[i] = new QuillFile(fileName[i], Strings::jpegMimeType);
        QObject::connect(quillFile[i], SIGNAL(imageAvailable(const QuillImageList)),
                         &loop, SLOT(quit()));
    }

    int initTime = time.elapsed();

    for (int i=0; i<numFiles; i++)
        quillFile[i]->setDisplayLevel(0);

    int displayLevelTime = time.elapsed();

    do
        loop.exec();
    while (Quill::isCalculationInProgress());

    int prepareTime = time.elapsed();

    for (int i=0; i<numFiles; i++)
        if (quillFile[i]->image(0).isNull()) {
            std::cout<<"Error: not all images are loaded!\n";
            return;
        }

    QImage beforeEdit = quillFile[0]->image(0);

    time.restart();

    for (int i=0; i<numFiles; i++) {
        QuillImageFilter *filter =
            QuillImageFilterFactory::createImageFilter(QuillImageFilter::Name_RedEyeDetection);
        filter->setOption(QuillImageFilter::Radius, QVariant(radius));
        filter->setOption(QuillImageFilter::Center, QVariant(center));
        quillFile[i]->runFilter(filter);
    }

    do
        loop.exec();
    while (Quill::isCalculationInProgress());

    int finalTime = time.elapsed();

    for (int i=0; i<numFiles; i++)
        if (quillFile[i]->image(0).isNull()) {
            std::cout<<"Error: not all images are edited!\n";
            return;
        }

    std::cout << "Initialize " << numFiles << " QuillFiles: "
             << initTime << "ms";

    std::cout << "Set display levels of " << numFiles << " QuillFiles: "
             << displayLevelTime - initTime << "ms" << "\n";

    std::cout << "Total prepare " << numFiles << " QuillFiles: "
             << prepareTime << "ms" << "\n";

    std::cout << "Use case edit response for " << numFiles << " QuillFiles: "
             << finalTime << "ms" << "\n";

    int differences = compare(quillFile[0]->image(0), beforeEdit);
    std::cout << differences << " pixels were changed by the edit." << "\n";

    for (int i=0; i<numFiles; i++) {
        delete quillFile[i];
        QFile::remove(fileName[i]);
    }
}
开发者ID:alinelena,项目名称:quill,代码行数:99,代码来源:redeye.cpp

示例8: getAccountFiles

// --- PUBLIC ---
void MainWindow::getAccountFiles(QString email, QString password)
{
    QTemporaryFile file;
    QString myfile;
    QString myMegals;

    if(file.open())
    {
        qDebug() << file.fileName();
        myfile = file.fileName()+QString("n");
        file.close();
    }

    megals = ui->txtMegals->text();

    myMegals = megals;

    // getting absolute path
    if (megals.mid(0,1) == ".\\") myMegals =  QDir::currentPath() + megals.mid(1);
    if (megals.mid(0,1) == "./") myMegals =  QDir::currentPath() + megals.mid(1);

    if (myos == "unix") {
        if (myMegals.right(4)==".exe") {
            myMegals =  "wine " + myMegals;
        }
    }

    // command line
    QString program = myMegals + " -e -u " + email +" -p " + password + " >> " + myfile;

    QByteArray ba = program.toLocal8Bit();
    const char *temppr = ba.data();
    system(temppr);

    QTreeWidgetItem *thisuser = new QTreeWidgetItem(ui->treeWidget);
       thisuser->setText(0, email);

    int count = 0;
    QFile inputFile(myfile);
    if (inputFile.open(QIODevice::ReadOnly))
    {
       QTextStream in(&inputFile);
       while ( !in.atEnd() )
       {
           QString line = in.readLine();
           if(line[0]==QChar('h')) {
               qDebug() << line.split(" ", QString::SkipEmptyParts).at(1);
               qDebug() << line.split(" ", QString::SkipEmptyParts).at(0);
               QTreeWidgetItem *fileItem = new QTreeWidgetItem(thisuser);
               fileItem->setText(0, line.mid(line.indexOf(" ")+1));
               fileItem->setText(1, line.split(" ", QString::SkipEmptyParts).at(0));
               count++;
           }
       }
    }

    if (count == 0) QMessageBox::critical(this,"Error","It was not possible to retrieve the list of " + email + "'s account files. There are three possible reasons: email or password are wrong, you are using a proxy to connect to internet, you do not have files uploaded into your account. Please take note that it is not possible to stream files if you are using a proxy and it's not possible to stream files that have not been uploaded to you account but have been shared from some other account.");
    inputFile.close();
    //remove file now
    QFile::remove(myfile);
    thisuser->setExpanded(true);
    ui->treeWidget->header()->resizeSections(QHeaderView::ResizeToContents);
}
开发者ID:mto89,项目名称:MEGAStream,代码行数:64,代码来源:mainwindow.cpp

示例9: replace

bool Manager::replace(const KileTemplate::Info& toBeReplaced, const QUrl &newTemplateSourceURL, const QString& newName, const QUrl& newIcon) {
	KileDocument::Type type = m_kileInfo->extensions()->determineDocumentType(newTemplateSourceURL);

	//start by copying the files that belong to the new template to a safe place
	QString templateTempFile, iconTempFile;

	if( newTemplateSourceURL.isLocalFile() ) {
		// file protocol. We do not need the network
		templateTempFile = newTemplateSourceURL.toLocalFile();
	}
	else {
		QTemporaryFile tmpFile;
		tmpFile.setAutoRemove( false );
		tmpFile.open();

		templateTempFile = tmpFile.fileName();
		m_TempFilePath = tmpFile.fileName();
		KIO::FileCopyJob* fileCopyJob = KIO::file_copy( newTemplateSourceURL, QUrl::fromLocalFile(templateTempFile), -1, KIO::Overwrite );
		KJobWidgets::setWindow( fileCopyJob, m_kileInfo->mainWindow() );

		if( ! fileCopyJob->exec() ) {
			return false;
		}
	}

	if( newIcon.isLocalFile() ) {
		// file protocol. We do not need the network
		iconTempFile = newIcon.toLocalFile();
	}
	else {
		QTemporaryFile tmpFile;
		tmpFile.setAutoRemove( false );
		tmpFile.open();

		iconTempFile = tmpFile.fileName();
		m_TempFilePath = tmpFile.fileName();
		KIO::FileCopyJob* fileCopyJob = KIO::file_copy( newIcon, QUrl::fromLocalFile(iconTempFile), -1, KIO::Overwrite );
		KJobWidgets::setWindow( fileCopyJob, m_kileInfo->mainWindow() );

		if( ! fileCopyJob->exec() ) {
			if( ! templateTempFile.isEmpty() )
				QFile::remove( templateTempFile );
			return false;
		}
	}

	//now delete the template that should be replaced
	if(!remove(toBeReplaced)) {
		if( ! templateTempFile.isEmpty() )
			QFile::remove( templateTempFile );
		if( ! iconTempFile.isEmpty() )
			QFile::remove( iconTempFile );
	}

	//finally, create the new template
	if(!add(QUrl::fromUserInput(templateTempFile), type, newName, QUrl::fromUserInput(iconTempFile))) {
		if( ! templateTempFile.isEmpty() )
			QFile::remove( templateTempFile );
		if( ! iconTempFile.isEmpty() )
			QFile::remove( iconTempFile );
		return false;
	}

	if( ! templateTempFile.isEmpty() )
			QFile::remove( templateTempFile );
	if( ! iconTempFile.isEmpty() )
			QFile::remove( iconTempFile );

	return true;
}
开发者ID:KDE,项目名称:kile,代码行数:70,代码来源:templates.cpp

示例10: Q_ASSERT

void TestPSD::testPSD() {

  Kst::VectorPtr vp = Kst::kst_cast<Kst::Vector>(_store.createObject<Kst::Vector>());
  Q_ASSERT(vp);
  vp->resize(10);
  vp->setDescriptiveName("tempVector");
  for (int i = 0; i < 10; i++){
    vp->value()[i] = i;
  }

  Kst::PSDPtr psd = Kst::kst_cast<Kst::PSD>(_store.createObject<Kst::PSD>());
  psd->change(vp, 0.0, false, 10, false, false, QString("vUnits"), QString("rUnits"), WindowUndefined, 0.0, PSDUndefined);
  QCOMPARE(psd->vector()->descriptiveName(), QLatin1String("tempVector"));
  QCOMPARE(psd->output(), PSDUndefined);
  QVERIFY(!psd->apodize());
  QVERIFY(!psd->removeMean());
  QVERIFY(!psd->average());
  QCOMPARE(psd->frequency(), 0.0);
  QCOMPARE(psd->apodizeFxn(), WindowUndefined);
  QCOMPARE(psd->gaussianSigma(), 0.0);
  Kst::VectorPtr vpVX = psd->vX();
  Kst::VectorPtr vpVY = psd->vY();

  QCOMPARE(vpVX->length(), 1);
  QVERIFY(vpVX->value()[0] != vpVX->value()[0]);
  QCOMPARE(vpVY->length(), 1);
  QVERIFY(vpVY->value()[0] != vpVY->value()[0]);

  for(int j = 0; j < vpVX->length(); j++){
      QCOMPARE(vpVX->value()[j], 0.0);
  }

  psd->setOutput(PSDAmplitudeSpectralDensity);
  psd->setApodize(true);
  psd->setRemoveMean(true);
  psd->setAverage(true);
  psd->setFrequency(0.1);
  psd->setApodizeFxn(WindowOriginal);
  psd->setGaussianSigma(0.2);

  QCOMPARE(psd->vector()->descriptiveName(), QLatin1String("tempVector"));
  QCOMPARE(psd->output(), PSDAmplitudeSpectralDensity);
  QVERIFY(psd->apodize());
  QVERIFY(psd->removeMean());
  QVERIFY(psd->average());
  QCOMPARE(psd->frequency(), 0.1);
  QCOMPARE(psd->apodizeFxn(), WindowOriginal);
  QCOMPARE(psd->gaussianSigma(), 0.2);

//   doTest(psd->update(0) == Kst::Object::UPDATE);
//   doTest(psd->propertyString() == ps);
//    doTest(!psd->curveHints().curveName() == "");
//   printf("Curve name [%s]", kstCHL[0].curveName());
//   printf("X Vector name [%s]", kstCHL[0].xVectorName());
//   printf("Y Vector name [%s]", kstCHL[0].yVectorName());

  QTemporaryFile tf;
  tf.open();
  QXmlStreamWriter xml;
  xml.setDevice(&tf);
  xml.setAutoFormatting(true);
  psd->save(xml);
  QFile::remove(tf.fileName());

  QDomNode n = makeDOMElement("psdDOMPsd", "psdDOMVector").firstChild();
  QDomElement e = n.toElement();

  //FIXME: should use factory, not this constructor.  This constructor is no longer
  // used anywhere in kst.
//   Kst::PSDPtr psdDOM = new Kst::PSD(&_store, e);

//   QCOMPARE(psdDOM->tag().tagString(), QLatin1String("psdDOMPsd"));
//   QCOMPARE(psdDOM->output(), PSDAmplitudeSpectralDensity);
//   QVERIFY(psdDOM->apodize());
//   QVERIFY(psdDOM->removeMean());
//   QVERIFY(psdDOM->average());
//   QCOMPARE(psdDOM->frequency(), 128.0);
//   QCOMPARE(psdDOM->apodizeFxn(), WindowOriginal);
//   QCOMPARE(psdDOM->gaussianSigma(), 0.01);

//   Kst::VectorPtr vpVX = psdDOM->vX();
//   for(int j = 0; j < vpVX->length(); j++){
//       printf("[%d][%lf]", j, vpVX->value()[j]);
//   }
//   Kst::VectorPtr vpVY = psdDOM->vY();
}
开发者ID:Kst-plot,项目名称:kst-subversion-archive,代码行数:86,代码来源:testpsd.cpp

示例11: Q_UNUSED

QgsVectorLayer* QgsRemoteDataSourceBuilder::vectorLayerFromRemoteVDS( const QDomElement& remoteVDSElem,
    const QString& layerName,
    QList<QTemporaryFile*>& filesToRemove,
    QList<QgsMapLayer*>& layersToRemove,
    bool allowCaching ) const
{
  Q_UNUSED( layerName );
  Q_UNUSED( allowCaching );
  QString providerString;
  QString formatString = remoteVDSElem.attribute( QStringLiteral( "format" ) );
  if ( formatString.compare( QLatin1String( "gml" ), Qt::CaseInsensitive ) == 0 )
  {
    providerString = QStringLiteral( "WFS" );
  }
  else
  {
    providerString = formatString;
  }

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

  QgsVectorLayer* vl = nullptr;

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

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

  //create vector layer

  //SOS has a special datasource key...
  if ( formatString.compare( QLatin1String( "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() ) )
  {
    QgsDebugMsg( "vl is not valid" );
  }

  layersToRemove.push_back( vl );
  filesToRemove.push_back( tmpFile );
  return vl;
}
开发者ID:,项目名称:,代码行数:65,代码来源:

示例12: logItem

void BootloaderInstallHex::installStage2(void)
{
    emit logItem(tr("Adding bootloader to firmware file"), LOGINFO);
    QCoreApplication::processEvents();

    // local temp file
    QTemporaryFile tempbin;
    tempbin.open();
    QString tempbinName = tempbin.fileName();
    tempbin.close();
    // get temporary files filenames -- external tools need this.
    m_descrambled.open();
    QString descrambledName = m_descrambled.fileName();
    m_descrambled.close();
    m_tempfile.open();
    QString tempfileName = m_tempfile.fileName();
    m_tempfile.close();

    int origin = 0;
    switch(m_model) {
        case 3:
            origin = 0x3f0000;
            break;
        case 2:
        case 1:
            origin = 0x1f0000;
            break;
        default:
            origin = 0;
            break;
    }

    // iriver decode already done in stage 1
    int result;
    if((result = mkboot(descrambledName.toLocal8Bit().constData(),
                    tempfileName.toLocal8Bit().constData(),
                    tempbinName.toLocal8Bit().constData(), origin)) < 0)
    {
        QString error;
        switch(result) {
            case -1: error = tr("could not open input file"); break;
            case -2: error = tr("reading header failed"); break;
            case -3: error = tr("reading firmware failed"); break;
            case -4: error = tr("can't open bootloader file"); break;
            case -5: error = tr("reading bootloader file failed"); break;
            case -6: error = tr("can't open output file"); break;
            case -7: error = tr("writing output file failed"); break;
        }
        emit logItem(tr("Error in patching: %1").arg(error), LOGERROR);

        emit done(true);
        return;
    }
    QTemporaryFile targethex;
    targethex.open();
    QString targethexName = targethex.fileName();
    if((result = iriver_encode(tempbinName.toLocal8Bit().constData(),
                    targethexName.toLocal8Bit().constData(), FALSE)) < 0)
    {
        emit logItem(tr("Error in scramble: %1").arg(scrambleError(result)), LOGERROR);
        targethex.close();

        emit done(true);
        return;
    }

    // finally check the md5sum of the created file
    QByteArray filedata;
    filedata = targethex.readAll();
    targethex.close();
    QString hash = QCryptographicHash::hash(filedata,
            QCryptographicHash::Md5).toHex();
    qDebug() << "[BootloaderInstallHex] created hexfile hash:" << hash;

    emit logItem(tr("Checking modified firmware file"), LOGINFO);
    if(hash != QString(md5sums[m_hashindex].patched)) {
        emit logItem(tr("Error: modified file checksum wrong"), LOGERROR);
        targethex.remove();
        emit done(true);
        return;
    }
    // finally copy file to player
    targethex.copy(m_blfile);

    emit logItem(tr("Success: modified firmware file created"), LOGINFO);
    logInstall(LogAdd);
    emit done(false);

    return;
}
开发者ID:a-martinez,项目名称:rockbox,代码行数:90,代码来源:bootloaderinstallhex.cpp

示例13: QStringList


//.........这里部分代码省略.........
  height = mParameters.value( QStringLiteral( "HEIGHT" ), QStringLiteral( "0" ) ).toInt( &conversionSuccess );
  if ( !conversionSuccess )
  {
    height = 0;
  }

  if ( width < 0 || height < 0 )
  {
    mErrors << QStringLiteral( "The WIDTH and HEIGHT are mandatory and have to be integer" );
  }

  crs = mParameters.value( QStringLiteral( "CRS" ), QLatin1String( "" ) );
  if ( crs == QLatin1String( "" ) )
  {
    mErrors << QStringLiteral( "The CRS is mandatory" );
  }

  if ( mErrors.count() != 0 )
  {
    throw QgsMapServiceException( QStringLiteral( "RequestNotWellFormed" ), mErrors.join( QStringLiteral( ". " ) ) );
  }

  QgsCoordinateReferenceSystem requestCRS = QgsCoordinateReferenceSystem::fromOgcWmsCrs( crs );
  if ( !requestCRS.isValid() )
  {
    mErrors << QStringLiteral( "Could not create request CRS" );
    throw QgsMapServiceException( QStringLiteral( "RequestNotWellFormed" ), mErrors.join( QStringLiteral( ". " ) ) );
  }

  QgsRectangle rect( minx, miny, maxx, maxy );

  QgsMapLayer* layer = layerList.at( 0 );
  QgsRasterLayer* rLayer = qobject_cast<QgsRasterLayer*>( layer );
  if ( rLayer && wcsLayersId.contains( rLayer->id() ) )
  {
#ifdef HAVE_SERVER_PYTHON_PLUGINS
    if ( !mAccessControl->layerReadPermission( rLayer ) )
    {
      throw QgsMapServiceException( QStringLiteral( "Security" ), QStringLiteral( "You are not allowed to access to this coverage" ) );
    }
#endif

    // RESPONSE_CRS
    QgsCoordinateReferenceSystem responseCRS = rLayer->crs();
    crs = mParameters.value( QStringLiteral( "RESPONSE_CRS" ), QLatin1String( "" ) );
    if ( crs != QLatin1String( "" ) )
    {
      responseCRS = QgsCoordinateReferenceSystem::fromOgcWmsCrs( crs );
      if ( !responseCRS.isValid() )
      {
        responseCRS = rLayer->crs();
      }
    }

    // transform rect
    if ( requestCRS != rLayer->crs() )
    {
      QgsCoordinateTransform t( requestCRS, rLayer->crs() );
      rect = t.transformBoundingBox( rect );
    }

    QTemporaryFile tempFile;
    tempFile.open();
    QgsRasterFileWriter fileWriter( tempFile.fileName() );

    // clone pipe/provider
    QgsRasterPipe* pipe = new QgsRasterPipe();
    if ( !pipe->set( rLayer->dataProvider()->clone() ) )
    {
      mErrors << QStringLiteral( "Cannot set pipe provider" );
      throw QgsMapServiceException( QStringLiteral( "RequestNotWellFormed" ), mErrors.join( QStringLiteral( ". " ) ) );
    }

    // add projector if necessary
    if ( responseCRS != rLayer->crs() )
    {
      QgsRasterProjector * projector = new QgsRasterProjector;
      projector->setCrs( rLayer->crs(), responseCRS );
      if ( !pipe->insert( 2, projector ) )
      {
        mErrors << QStringLiteral( "Cannot set pipe projector" );
        throw QgsMapServiceException( QStringLiteral( "RequestNotWellFormed" ), mErrors.join( QStringLiteral( ". " ) ) );
      }
    }

    QgsRasterFileWriter::WriterError err = fileWriter.writeRaster( pipe, width, height, rect, responseCRS );
    if ( err != QgsRasterFileWriter::NoError )
    {
      mErrors << QStringLiteral( "Cannot write raster error code: %1" ).arg( err );
      throw QgsMapServiceException( QStringLiteral( "RequestNotWellFormed" ), mErrors.join( QStringLiteral( ". " ) ) );
    }
    delete pipe;
    QByteArray* ba = nullptr;
    ba = new QByteArray();
    *ba = tempFile.readAll();

    return ba;
  }
  return nullptr;
}
开发者ID:,项目名称:,代码行数:101,代码来源:

示例14: kDebug


//.........这里部分代码省略.........
            if (meta.getExifTagLong("Exif.Photo.FocalLengthIn35mmFilm", val))    exif->fFocalLengthIn35mmFilm    = (uint32)val;
            if (meta.getExifTagLong("Exif.Photo.ComponentsConfiguration", val))  exif->fComponentsConfiguration  = (uint32)val;
            if (meta.getExifTagLong("Exif.Photo.PixelXDimension", val))          exif->fPixelXDimension          = (uint32)val;
            if (meta.getExifTagLong("Exif.Photo.PixelYDimension", val))          exif->fPixelYDimension          = (uint32)val;
            if (meta.getExifTagLong("Exif.Photo.FocalPlaneResolutionUnit", val)) exif->fFocalPlaneResolutionUnit = (uint32)val;
            if (meta.getExifTagLong("Exif.GPSInfo.GPSVersionID", val))           exif->fGPSVersionID             = (uint32)val;
            if (meta.getExifTagLong("Exif.GPSInfo.GPSAltitudeRef", val))         exif->fGPSAltitudeRef           = (uint32)val;
            if (meta.getExifTagLong("Exif.GPSInfo.GPSDifferential", val))        exif->fGPSDifferential          = (uint32)val;
        }

        // Markernote backup.

        QByteArray mkrnts = meta.getExifTagData("Exif.Photo.MakerNote");
        if (!mkrnts.isEmpty())
        {
            kDebug( 51000 ) << "DNGWriter: Backup Makernote (" << mkrnts.size() << " bytes)" << endl;

            dng_memory_allocator memalloc(gDefaultDNGMemoryAllocator);
            dng_memory_stream stream(memalloc);
            stream.Put(mkrnts.data(), mkrnts.size());
            AutoPtr<dng_memory_block> block(host.Allocate(mkrnts.size()));
            stream.SetReadPosition(0);
            stream.Get(block->Buffer(), mkrnts.size());
            negative->SetMakerNote(block);
            negative->SetMakerNoteSafety(true);
        }

        if (d->backupOriginalRawFile)
        {
            kDebug( 51000 ) << "DNGWriter: Backup Original RAW file (" << inputInfo.size() << " bytes)" << endl;

            // Compress Raw file data to Zip archive.

            QTemporaryFile zipFile;
            if (!zipFile.open())
            {
                kDebug( 51000 ) << "DNGWriter: Cannot open temporary file to write Zip Raw file. Aborted..." << endl;
                return -1;
            }
            KZip zipArchive(zipFile.fileName());
            zipArchive.open(QIODevice::WriteOnly);
            zipArchive.setCompression(KZip::DeflateCompression);
            zipArchive.addLocalFile(inputFile(), inputFile());
            zipArchive.close();

            // Load Zip Archive in a byte array

            QFileInfo zipFileInfo(zipFile.fileName());
            QByteArray zipRawFileData;
            zipRawFileData.resize(zipFileInfo.size());
            QDataStream dataStream(&zipFile);
            dataStream.readRawData(zipRawFileData.data(), zipRawFileData.size());
            kDebug( 51000 ) << "DNGWriter: Zipped RAW file size " << zipRawFileData.size() << " bytes" << endl;

            // Pass byte array to DNG sdk and compute MD5 fingerprint.

            dng_memory_allocator memalloc(gDefaultDNGMemoryAllocator);
            dng_memory_stream stream(memalloc);
            stream.Put(zipRawFileData.data(), zipRawFileData.size());
            AutoPtr<dng_memory_block> block(host.Allocate(zipRawFileData.size()));
            stream.SetReadPosition(0);
            stream.Get(block->Buffer(), zipRawFileData.size());

            dng_md5_printer md5;
            md5.Process(block->Buffer(), block->LogicalSize());
            negative->SetOriginalRawFileData(block);
开发者ID:ruphy,项目名称:kipi-plugins,代码行数:67,代码来源:dngwriter.cpp

示例15: kDebug

bool EPSHandler::read(QImage *image)
{
    kDebug(399) << "kimgio EPS: starting...";

    FILE * ghostfd;
    int x1, y1, x2, y2;
    //QTime dt;
    //dt.start();

    QString cmdBuf;
    QString tmp;

    QIODevice* io = device();
    quint32 ps_offset, ps_size;

    // find start of PostScript code
    if ( !seekToCodeStart(io, ps_offset, ps_size) )
        return false;

    // find bounding box
    if ( !bbox (io, &x1, &y1, &x2, &y2)) {
        kError(399) << "kimgio EPS: no bounding box found!" << endl;
        return false;
    }

    QTemporaryFile tmpFile;
    if( !tmpFile.open() ) {
        kError(399) << "kimgio EPS: no temp file!" << endl;
        return false;
    }

    // x1, y1 -> translation
    // x2, y2 -> new size

    x2 -= x1;
    y2 -= y1;
    //kDebug(399) << "origin point: " << x1 << "," << y1 << "  size:" << x2 << "," << y2;
    double xScale = 1.0;
    double yScale = 1.0;
    int wantedWidth = x2;
    int wantedHeight = y2;

    // create GS command line

    cmdBuf = "gs -sOutputFile=";
    cmdBuf += tmpFile.fileName();
    cmdBuf += " -q -g";
    tmp.setNum( wantedWidth );
    cmdBuf += tmp;
    tmp.setNum( wantedHeight );
    cmdBuf += 'x';
    cmdBuf += tmp;
    cmdBuf += " -dSAFER -dPARANOIDSAFER -dNOPAUSE -sDEVICE=ppm -c "
              "0 0 moveto "
              "1000 0 lineto "
              "1000 1000 lineto "
              "0 1000 lineto "
              "1 1 254 255 div setrgbcolor fill "
              "0 0 0 setrgbcolor - -c showpage quit";

    // run ghostview

    ghostfd = popen (QFile::encodeName(cmdBuf), "w");

    if ( ghostfd == 0 ) {
        kError(399) << "kimgio EPS: no GhostScript?" << endl;
        return false;
    }

    fprintf (ghostfd, "\n%d %d translate\n", -qRound(x1*xScale), -qRound(y1*yScale));

    // write image to gs

    io->reset(); // Go back to start of file to give all the file to GhostScript
    if (ps_offset>0L) // We have an offset
        io->seek(ps_offset);
    QByteArray buffer ( io->readAll() );

    // If we have no MS-DOS EPS file or if the size seems wrong, then choose the buffer size
    if (ps_size<=0 || ps_size>(unsigned int)buffer.size())
        ps_size=buffer.size();

    fwrite(buffer.data(), sizeof(char), ps_size, ghostfd);
    buffer.resize(0);

    pclose ( ghostfd );

    // load image
    if( image->load (tmpFile.fileName()) ) {
        kDebug(399) << "kimgio EPS: success!";
        //kDebug(399) << "Loading EPS took " << (float)(dt.elapsed()) / 1000 << " seconds";
        return true;
    }

    kError(399) << "kimgio EPS: no image!" << endl;
    return false;
}
开发者ID:,项目名称:,代码行数:97,代码来源:


注:本文中的QTemporaryFile类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。