本文整理汇总了C++中QTemporaryFile::open方法的典型用法代码示例。如果您正苦于以下问题:C++ QTemporaryFile::open方法的具体用法?C++ QTemporaryFile::open怎么用?C++ QTemporaryFile::open使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类QTemporaryFile
的用法示例。
在下文中一共展示了QTemporaryFile::open方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: checkCode
/* Purpose: calls external static code test tool and display it's results
TODO: call only selected part of code (if something is selected)
*/
void toPLSQLEditor::checkCode(void)
{
if (currentEditor()->editor()->text().isEmpty())
{
// do nothing if code text is empty
return;
}
QTemporaryFile tf;
if (tf.open())
{
if (!toWriteFile(tf.fileName(), currentEditor()->editor()->text()))
{
#ifdef DEBUG
qDebug() << "Unable to write file (" + tf.fileName() + ")";
#endif
return;
}
else
{
#ifdef DEBUG
qDebug() << "Success!!! Temporary file " + tf.fileName();
#endif
}
}
QString program = toConfigurationSingle::Instance().staticChecker().arg(tf.fileName());
#ifdef DEBUG
qDebug() << "program to be executed: " + program;
#endif
QProcess staticCheck(qApp);
staticCheck.setProcessChannelMode(QProcess::MergedChannels);
staticCheck.start(program);
staticCheck.waitForFinished(); // default timeout - 30000 miliseconds
int exit_code = staticCheck.exitStatus();
if (exit_code != 0)
{
#ifdef DEBUG
qDebug() << "Error executing static check. Exit code = " << exit_code;
int run_error = staticCheck.error();
// error values taken from Qt4.6 documentation for QProcess
switch (run_error)
{
case 0:
qDebug() << "The process failed to start. Either the invoked program is missing, or you may have insufficient permissions to invoke the program.";
break;
case 1:
qDebug() << "The process crashed some time after starting successfully.";
break;
case 5:
qDebug() << "An unknown error occurred.";
break;
default:
qDebug() << "Error code: " << run_error << "--" << staticCheck.errorString();
} // switch
#endif
return;
}
QString qq = staticCheck.readAllStandardOutput();
#ifdef DEBUG
qDebug() << "stdout" << qq;
#endif
QMultiMap<int, QString> Observations;
parseResults(qq, Observations);
currentEditor()->editor()->setErrors(Observations, false);
currentEditor()->applyResult("STATIC", Observations);
currentEditor()->resizeResults();
} // checkCode
示例2: GetSurfaceForPrinter
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;
}
示例3: save
void HistoryManager::save()
{
QSettings settings;
settings.beginGroup(QLatin1String("history"));
settings.setValue(QLatin1String("historyLimit"), m_historyLimit);
bool saveAll = m_lastSavedUrl.isEmpty();
int first = m_history.count() - 1;
if (!saveAll) {
// find the first one to save
for (int i = 0; i < m_history.count(); ++i) {
if (m_history.at(i).url == m_lastSavedUrl) {
first = i - 1;
break;
}
}
}
if (first == m_history.count() - 1)
saveAll = true;
QString directory = QDesktopServices::storageLocation(QDesktopServices::DataLocation);
if (directory.isEmpty())
directory = QDir::homePath() + QLatin1String("/.") + QCoreApplication::applicationName();
if (!QFile::exists(directory)) {
QDir dir;
dir.mkpath(directory);
}
QFile historyFile(directory + QLatin1String("/history"));
// When saving everything use a temporary file to prevent possible data loss.
QTemporaryFile tempFile;
tempFile.setAutoRemove(false);
bool open = false;
if (saveAll) {
open = tempFile.open();
} else {
open = historyFile.open(QFile::Append);
}
if (!open) {
qWarning() << "Unable to open history file for saving"
<< (saveAll ? tempFile.fileName() : historyFile.fileName());
return;
}
QDataStream out(saveAll ? &tempFile : &historyFile);
for (int i = first; i >= 0; --i) {
QByteArray data;
QDataStream stream(&data, QIODevice::WriteOnly);
HistoryItem item = m_history.at(i);
stream << HISTORY_VERSION << item.url << item.dateTime << item.title;
out << data;
}
tempFile.close();
if (saveAll) {
if (historyFile.exists() && !historyFile.remove())
qWarning() << "History: error removing old history." << historyFile.errorString();
if (!tempFile.rename(historyFile.fileName()))
qWarning() << "History: error moving new history over old." << tempFile.errorString() << historyFile.fileName();
}
m_lastSavedUrl = m_history.value(0).url;
}
示例4: ExtractTar
bool Packaging::ExtractTar(QTemporaryFile& tarFile, PackageData *packageData)
{
TarHeader tarHeader;
if (!tarFile.open())
{
Alerts::DisplayError(QString("Error opening temporary TAR archive:\n%1").arg(tarFile.fileName()));
return (false);
}
bool previousEmpty = false;
QProgressDialog progressDialog("Extracting files...", "Cancel", 0, tarFile.size());
progressDialog.setWindowModality(Qt::ApplicationModal);
progressDialog.setWindowTitle("Heimdall Frontend");
while (!tarFile.atEnd())
{
qint64 dataRead = tarFile.read(tarHeader.buffer, TarHeader::kBlockLength);
if (dataRead != TarHeader::kBlockLength)
{
progressDialog.close();
Alerts::DisplayError("Package's TAR archive is malformed.");
tarFile.close();
return (false);
}
progressDialog.setValue(tarFile.pos());
if (progressDialog.wasCanceled())
{
tarFile.close();
progressDialog.close();
return (false);
}
//bool ustarFormat = strcmp(tarHeader.fields.magic, ustarMagic) == 0;
bool empty = true;
for (int i = 0; i < TarHeader::kBlockLength; i++)
{
if (tarHeader.buffer[i] != 0)
{
empty = false;
break;
}
}
if (empty)
{
if (previousEmpty)
{
// Two empty blocks in a row means we've reached the end of the archive.
break;
}
}
else
{
int checksum = 0;
for (char *bufferIndex = tarHeader.buffer; bufferIndex < tarHeader.fields.checksum; bufferIndex++)
checksum += static_cast<unsigned char>(*bufferIndex);
checksum += 8 * ' ';
checksum += static_cast<unsigned char>(tarHeader.fields.typeFlag);
// Both the TAR and USTAR formats have terrible documentation, it's not clear if the following code is required.
/*if (ustarFormat)
{
for (char *bufferIndex = tarHeader.fields.linkName; bufferIndex < tarHeader.fields.prefix + 155; bufferIndex++)
checksum += static_cast<unsigned char>(*bufferIndex);
}*/
bool parsed = false;
// The size field is not always null terminated, so we must create a copy and null terminate it for parsing.
char fileSizeString[13];
memcpy(fileSizeString, tarHeader.fields.size, 12);
fileSizeString[12] = '\0';
qulonglong fileSize = QString(fileSizeString).toULongLong(&parsed, 8);
if (!parsed)
{
progressDialog.close();
Alerts::DisplayError("Tar header contained an invalid file size.");
tarFile.close();
return (false);
}
if (fileSize > 0 && tarHeader.fields.typeFlag == '0')
{
// We're working with a file.
QString filename = QString::fromUtf8(tarHeader.fields.name);
//.........这里部分代码省略.........
示例5: AddJob
int TorrentPlugin::AddJob (Entity e)
{
QString suggestedFname;
if (e.Entity_.canConvert<QUrl> ())
{
QUrl resource = e.Entity_.toUrl ();
if (resource.scheme () == "magnet")
{
QString at = XmlSettingsManager::Instance ()->
property ("AutomaticTags").toString ();
QStringList tags = e.Additional_ [" Tags"].toStringList ();
Q_FOREACH (QString tag, Core::Instance ()->GetProxy ()->
GetTagsManager ()->Split (at))
tags << Core::Instance ()->GetProxy ()->
GetTagsManager ()->GetID (tag);
QList<QPair<QString, QString> > queryItems = resource.queryItems ();
for (QList<QPair<QString, QString> >::const_iterator i = queryItems.begin (),
end = queryItems.end (); i != end; ++i)
if (i->first == "kt")
{
QStringList humanReadable = i->second
.split ('+', QString::SkipEmptyParts);
Q_FOREACH (QString hr, humanReadable)
tags += Core::Instance ()->GetProxy ()->
GetTagsManager ()->GetID (hr);
}
return Core::Instance ()->AddMagnet (resource.toString (),
e.Location_,
tags,
e.Parameters_);
}
else if (resource.scheme () == "file")
suggestedFname = resource.toLocalFile ();
}
QByteArray entity = e.Entity_.toByteArray ();
QFile file (suggestedFname);
if ((!file.exists () ||
!file.open (QIODevice::ReadOnly)) &&
Core::Instance ()->IsValidTorrent (entity))
{
QTemporaryFile file ("lctemporarybittorrentfile.XXXXXX");
if (!file.open ())
return -1;
file.write (entity);
suggestedFname = file.fileName ().toUtf8 ();
file.setAutoRemove (false);
}
AddTorrentDialog_->Reinit ();
AddTorrentDialog_->SetFilename (suggestedFname);
if (!e.Location_.isEmpty ())
AddTorrentDialog_->SetSavePath (e.Location_);
QString path;
QStringList tags = e.Additional_ [" Tags"].toStringList ();
QVector<bool> files;
QString fname;
bool tryLive = e.Additional_ ["TryToStreamLive"].toBool ();
if (e.Parameters_ & FromUserInitiated)
{
if (!tags.isEmpty ())
AddTorrentDialog_->SetTags (tags);
if (AddTorrentDialog_->exec () == QDialog::Rejected)
return -1;
fname = AddTorrentDialog_->GetFilename (),
path = AddTorrentDialog_->GetSavePath ();
tryLive = AddTorrentDialog_->GetTryLive ();
files = AddTorrentDialog_->GetSelectedFiles ();
tags = AddTorrentDialog_->GetTags ();
if (AddTorrentDialog_->GetAddType () == Core::Started)
e.Parameters_ &= ~NoAutostart;
else
e.Parameters_ |= NoAutostart;
}
else
{
fname = suggestedFname;
path = e.Location_;
QString at = XmlSettingsManager::Instance ()->
property ("AutomaticTags").toString ();
Q_FOREACH (QString tag, Core::Instance ()->GetProxy ()->
GetTagsManager ()->Split (at))
tags << Core::Instance ()->GetProxy ()->
GetTagsManager ()->GetID (tag);
}
int result = Core::Instance ()->AddFile (fname,
path,
tags,
tryLive,
files,
e.Parameters_);
setActionsEnabled ();
file.remove ();
//.........这里部分代码省略.........
示例6: 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;
}
示例7: runRdb
void runRdb( uint flags )
{
// Obtain the application palette that is about to be set.
bool exportColors = flags & KRdbExportColors;
bool exportQtColors = flags & KRdbExportQtColors;
bool exportQtSettings = flags & KRdbExportQtSettings;
bool exportXftSettings = flags & KRdbExportXftSettings;
bool exportGtkTheme = flags & KRdbExportGtkTheme;
KSharedConfigPtr kglobalcfg = KSharedConfig::openConfig( QStringLiteral("kdeglobals") );
KConfigGroup kglobals(kglobalcfg, "KDE");
QPalette newPal = KColorScheme::createApplicationPalette(kglobalcfg);
QTemporaryFile tmpFile;
if (!tmpFile.open())
{
qDebug() << "Couldn't open temp file";
exit(0);
}
KConfigGroup generalCfgGroup(kglobalcfg, "General");
QString gtkTheme;
if (kglobals.hasKey("widgetStyle"))
gtkTheme = kglobals.readEntry("widgetStyle");
else
gtkTheme = QStringLiteral("oxygen");
createGtkrc( exportColors, newPal, exportGtkTheme, gtkTheme, 1 );
createGtkrc( exportColors, newPal, exportGtkTheme, gtkTheme, 2 );
// Export colors to non-(KDE/Qt) apps (e.g. Motif, GTK+ apps)
if (exportColors)
{
KConfigGroup g(KSharedConfig::openConfig(), "WM");
QString preproc;
QColor backCol = newPal.color( QPalette::Active, QPalette::Background );
addColorDef(preproc, "FOREGROUND" , newPal.color( QPalette::Active, QPalette::Foreground ) );
addColorDef(preproc, "BACKGROUND" , backCol);
addColorDef(preproc, "HIGHLIGHT" , backCol.light(100+(2*KColorScheme::contrast()+4)*16/1));
addColorDef(preproc, "LOWLIGHT" , backCol.dark(100+(2*KColorScheme::contrast()+4)*10));
addColorDef(preproc, "SELECT_BACKGROUND" , newPal.color( QPalette::Active, QPalette::Highlight));
addColorDef(preproc, "SELECT_FOREGROUND" , newPal.color( QPalette::Active, QPalette::HighlightedText));
addColorDef(preproc, "WINDOW_BACKGROUND" , newPal.color( QPalette::Active, QPalette::Base ) );
addColorDef(preproc, "WINDOW_FOREGROUND" , newPal.color( QPalette::Active, QPalette::Text ) );
addColorDef(preproc, "INACTIVE_BACKGROUND", g.readEntry("inactiveBackground", QColor(224, 223, 222)));
addColorDef(preproc, "INACTIVE_FOREGROUND", g.readEntry("inactiveBackground", QColor(224, 223, 222)));
addColorDef(preproc, "ACTIVE_BACKGROUND" , g.readEntry("activeBackground", QColor(48, 174, 232)));
addColorDef(preproc, "ACTIVE_FOREGROUND" , g.readEntry("activeBackground", QColor(48, 174, 232)));
//---------------------------------------------------------------
tmpFile.write( preproc.toLatin1(), preproc.length() );
QStringList list;
const QStringList adPaths = QStandardPaths::locateAll(QStandardPaths::GenericDataLocation,
QStringLiteral("kdisplay/app-defaults/"), QStandardPaths::LocateDirectory);
for (QStringList::ConstIterator it = adPaths.constBegin(); it != adPaths.constEnd(); ++it) {
QDir dSys( *it );
if ( dSys.exists() ) {
dSys.setFilter( QDir::Files );
dSys.setSorting( QDir::Name );
dSys.setNameFilters(QStringList(QStringLiteral("*.ad")));
list += dSys.entryList();
}
}
for (QStringList::ConstIterator it = list.constBegin(); it != list.constEnd(); ++it)
copyFile(tmpFile, QStandardPaths::locate(QStandardPaths::GenericDataLocation, "kdisplay/app-defaults/"+(*it)), true);
}
// Merge ~/.Xresources or fallback to ~/.Xdefaults
QString homeDir = QDir::homePath();
QString xResources = homeDir + "/.Xresources";
// very primitive support for ~/.Xresources by appending it
if ( QFile::exists( xResources ) )
copyFile(tmpFile, xResources, true);
else
copyFile(tmpFile, homeDir + "/.Xdefaults", true);
// Export the Xcursor theme & size settings
KConfigGroup mousecfg(KSharedConfig::openConfig( QStringLiteral("kcminputrc") ), "Mouse" );
QString theme = mousecfg.readEntry("cursorTheme", QString());
QString size = mousecfg.readEntry("cursorSize", QString());
QString contents;
if (!theme.isNull())
contents = "Xcursor.theme: " + theme + '\n';
if (!size.isNull())
contents += "Xcursor.size: " + size + '\n';
if (exportXftSettings)
{
if (generalCfgGroup.hasKey("XftAntialias"))
{
contents += QLatin1String("Xft.antialias: ");
//.........这里部分代码省略.........
示例8: 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]);
}
}
示例9: testRevertRestore
void ut_file::testRevertRestore()
{
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 imageAfter = filter->apply(image);
QuillFile *file = new QuillFile(testFile.fileName(), Strings::png);
QVERIFY(file->setDisplayLevel(0));
QCOMPARE(file->canRestore(),false);
QCOMPARE(file->canRevert(),false);
file->runFilter(filter);
Quill::releaseAndWait();
Quill::releaseAndWait();
QCOMPARE(file->canRestore(),false);
QCOMPARE(file->canRevert(),true);
QuillImageFilter *filter1 =
QuillImageFilterFactory::createImageFilter(QuillImageFilter::Name_Rotate);
filter1->setOption(QuillImageFilter::Angle, QVariant(-90));
QuillImage imageAfter1 = filter1->apply(imageAfter);
file->runFilter(filter1);
Quill::releaseAndWait();
Quill::releaseAndWait();
QCOMPARE(file->canRestore(),false);
QCOMPARE(file->canRevert(),true);
//Test revert
file->revert();
Quill::releaseAndWait();
Quill::releaseAndWait();
QCOMPARE(file->canRestore(),true);
QCOMPARE(file->canRevert(),false);
QCOMPARE(file->internalFile()->m_stack->revertIndex(),3);
QVERIFY(Unittests::compareImage(file->image(), image));
file->save();
Quill::releaseAndWait();
Quill::releaseAndWait();
//Test restore
file->restore();
Quill::releaseAndWait();
Quill::releaseAndWait();
QCOMPARE(file->canRestore(),false);
QCOMPARE(file->canRevert(),true);
QCOMPARE(file->internalFile()->m_stack->revertIndex(),0);
QVERIFY(Unittests::compareImage(file->image(), imageAfter1));
//Test redo with revert and restore
file->revert();
Quill::releaseAndWait();
Quill::releaseAndWait();
QCOMPARE(file->canRestore(),true);
QCOMPARE(file->canRevert(),false);
QCOMPARE(file->internalFile()->m_stack->revertIndex(),3);
file->redo();
QCOMPARE(file->canRestore(),false);
QCOMPARE(file->canRevert(),true);
QCOMPARE(file->internalFile()->m_stack->revertIndex(),0);
//Test one additional operation after revert
file->revert();
Quill::releaseAndWait();
Quill::releaseAndWait();
QCOMPARE(file->canRestore(),true);
QCOMPARE(file->canRevert(),false);
QCOMPARE(file->internalFile()->m_stack->revertIndex(),2);
QuillImageFilter *filter2 =
QuillImageFilterFactory::createImageFilter(QuillImageFilter::Name_Rotate);
filter2->setOption(QuillImageFilter::Angle, QVariant(-90));
file->runFilter(filter2);
QCOMPARE(file->canRestore(),false);
QCOMPARE(file->canRevert(),true);
QCOMPARE(file->internalFile()->m_stack->revertIndex(),0);
delete file;
}
示例10: paymentServerTests
//.........这里部分代码省略.........
// Validly signed, but by a CA not in our root CA list:
data = DecodeBase64(paymentrequest5_cert1_BASE64);
r = handleRequest(server, data);
r.paymentRequest.getMerchant(caStore, merchant);
QCOMPARE(merchant, QString(""));
// Try again with no root CA's, verifiedMerchant should be empty:
caStore = X509_STORE_new();
PaymentServer::LoadRootCAs(caStore);
data = DecodeBase64(paymentrequest1_cert1_BASE64);
r = handleRequest(server, data);
r.paymentRequest.getMerchant(caStore, merchant);
QCOMPARE(merchant, QString(""));
// Load second root certificate
caStore = X509_STORE_new();
X509_STORE_add_cert(caStore, parse_b64der_cert(caCert2_BASE64));
PaymentServer::LoadRootCAs(caStore);
QByteArray byteArray;
// For the tests below we just need the payment request data from
// paymentrequestdata.h parsed + stored in r.paymentRequest.
//
// These tests require us to bypass the following normal client execution flow
// shown below to be able to explicitly just trigger a certain condition!
//
// handleRequest()
// -> PaymentServer::eventFilter()
// -> PaymentServer::handleURIOrFile()
// -> PaymentServer::readPaymentRequestFromFile()
// -> PaymentServer::processPaymentRequest()
// Contains a testnet paytoaddress, so payment request network doesn't match client network:
data = DecodeBase64(paymentrequest1_cert2_BASE64);
byteArray = QByteArray((const char*)&data[0], data.size());
r.paymentRequest.parse(byteArray);
// Ensure the request is initialized, because network "main" is default, even for
// uninitialized payment requests and that will fail our test here.
QVERIFY(r.paymentRequest.IsInitialized());
QCOMPARE(PaymentServer::verifyNetwork(r.paymentRequest.getDetails()), false);
// Expired payment request (expires is set to 1 = 1970-01-01 00:00:01):
data = DecodeBase64(paymentrequest2_cert2_BASE64);
byteArray = QByteArray((const char*)&data[0], data.size());
r.paymentRequest.parse(byteArray);
// Ensure the request is initialized
QVERIFY(r.paymentRequest.IsInitialized());
// compares 1 < GetTime() == false (treated as expired payment request)
QCOMPARE(PaymentServer::verifyExpired(r.paymentRequest.getDetails()), true);
// Unexpired payment request (expires is set to 0x7FFFFFFFFFFFFFFF = max. int64_t):
// 9223372036854775807 (uint64), 9223372036854775807 (int64_t) and -1 (int32_t)
// -1 is 1969-12-31 23:59:59 (for a 32 bit time values)
data = DecodeBase64(paymentrequest3_cert2_BASE64);
byteArray = QByteArray((const char*)&data[0], data.size());
r.paymentRequest.parse(byteArray);
// Ensure the request is initialized
QVERIFY(r.paymentRequest.IsInitialized());
// compares 9223372036854775807 < GetTime() == false (treated as unexpired payment request)
QCOMPARE(PaymentServer::verifyExpired(r.paymentRequest.getDetails()), false);
// Unexpired payment request (expires is set to 0x8000000000000000 > max. int64_t, allowed uint64):
// 9223372036854775808 (uint64), -9223372036854775808 (int64_t) and 0 (int32_t)
// 0 is 1970-01-01 00:00:00 (for a 32 bit time values)
data = DecodeBase64(paymentrequest4_cert2_BASE64);
byteArray = QByteArray((const char*)&data[0], data.size());
r.paymentRequest.parse(byteArray);
// Ensure the request is initialized
QVERIFY(r.paymentRequest.IsInitialized());
// compares -9223372036854775808 < GetTime() == true (treated as expired payment request)
QCOMPARE(PaymentServer::verifyExpired(r.paymentRequest.getDetails()), true);
// Test BIP70 DoS protection:
unsigned char randData[BIP70_MAX_PAYMENTREQUEST_SIZE + 1];
GetRandBytes(randData, sizeof(randData));
// Write data to a temp file:
QTemporaryFile tempFile;
tempFile.open();
tempFile.write((const char*)randData, sizeof(randData));
tempFile.close();
// compares 50001 <= BIP70_MAX_PAYMENTREQUEST_SIZE == false
QCOMPARE(PaymentServer::verifySize(tempFile.size()), false);
// Payment request with amount overflow (amount is set to 21000001 BTC):
data = DecodeBase64(paymentrequest5_cert2_BASE64);
byteArray = QByteArray((const char*)&data[0], data.size());
r.paymentRequest.parse(byteArray);
// Ensure the request is initialized
QVERIFY(r.paymentRequest.IsInitialized());
// Extract address and amount from the request
QList<std::pair<CScript, CAmount> > sendingTos = r.paymentRequest.getPayTo();
for (const std::pair<CScript, CAmount>& sendingTo : sendingTos) {
CTxDestination dest;
if (ExtractDestination(sendingTo.first, dest))
QCOMPARE(PaymentServer::verifyAmount(sendingTo.second), false);
}
delete server;
}
示例11: doTests
void doTests() {
KstVectorPtr vp = new KstVector(KstObjectTag::fromString("tempVector"), 10);
for (int i = 0; i < 10; i++){
vp->value()[i] = i;
}
KstPSDPtr psd = new KstPSD(QString("psdTest"), vp, 0.0, false, 10, false, false, QString("vUnits"), QString("rUnits"), WindowUndefined, 0.0, PSDUndefined);
doTest(psd->tagName() == "psdTest");
doTest(psd->vTag() == "tempVector");
doTest(psd->output() == PSDUndefined);
doTest(!psd->apodize());
doTest(!psd->removeMean());
doTest(!psd->average());
doTest(psd->freq() == 0.0);
doTest(psd->apodizeFxn() == WindowUndefined);
doTest(psd->gaussianSigma() == 0);
KstVectorPtr vpVX = psd->vX();
KstVectorPtr vpVY = psd->vY();
doTest(vpVX->length() == 1);
doTest(vpVX->value()[0] != vpVX->value()[0]);
doTest(vpVY->length() == 1);
doTest(vpVY->value()[0] != vpVY->value()[0]);
psd->writeLock();
doTest(psd->update(0) == KstObject::UPDATE);
psd->unlock();
for(int j = 0; j < vpVX->length(); j++){
doTest(vpVX->value()[j] == 0);
}
psd->setOutput(PSDAmplitudeSpectralDensity);
psd->setApodize(true);
psd->setRemoveMean(true);
psd->setAverage(true);
psd->setFreq(0.1);
psd->setApodizeFxn(WindowOriginal);
psd->setGaussianSigma(0.2);
doTest(psd->tagName() == "psdTest");
doTest(psd->vTag() == "tempVector");
doTest(psd->output() == PSDAmplitudeSpectralDensity);
doTest(psd->apodize());
doTest(psd->removeMean());
doTest(psd->average());
doTest(psd->freq() == 0.1);
doTest(psd->apodizeFxn() == WindowOriginal);
doTest(psd->gaussianSigma() == 0.2);
// doTest(psd->update(0) == KstObject::UPDATE);
// QString ps = "PSD: " + psd->vTag();
// 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();
QTextStream ts(&tf);
psd->save(ts, "");
QFile::remove(tf.fileName());
QDomNode n = makeDOMElement("psdDOMPsd", "psdDOMVector").firstChild();
QDomElement e = n.toElement();
KstPSDPtr psdDOM = new KstPSD(e);
doTest(psdDOM->tagName() == "psdDOMPsd");
doTest(psdDOM->output() == PSDAmplitudeSpectralDensity);
doTest(psdDOM->apodize());
doTest(psdDOM->removeMean());
doTest(psdDOM->average());
doTest(psdDOM->freq() == 128);
doTest(psdDOM->apodizeFxn() == WindowOriginal);
doTest(psdDOM->gaussianSigma() == 0.01);
// KstVectorPtr vpVX = psdDOM->vX();
// for(int j = 0; j < vpVX->length(); j++){
// printf("[%d][%lf]", j, vpVX->value()[j]);
// }
// KstVectorPtr vpVY = psdDOM->vY();
}
示例12: savedFileForSnapshot
QFile* Snapshot::savedFileForSnapshot(bool isTemporary) {
auto glCanvas = DependencyManager::get<GLCanvas>();
QImage shot = glCanvas->grabFrameBuffer();
Avatar* avatar = Application::getInstance()->getAvatar();
glm::vec3 location = avatar->getPosition();
glm::quat orientation = avatar->getHead()->getOrientation();
// add metadata
shot.setText(LOCATION_X, QString::number(location.x));
shot.setText(LOCATION_Y, QString::number(location.y));
shot.setText(LOCATION_Z, QString::number(location.z));
shot.setText(ORIENTATION_X, QString::number(orientation.x));
shot.setText(ORIENTATION_Y, QString::number(orientation.y));
shot.setText(ORIENTATION_Z, QString::number(orientation.z));
shot.setText(ORIENTATION_W, QString::number(orientation.w));
shot.setText(DOMAIN_KEY, DependencyManager::get<NodeList>()->getDomainHandler().getHostname());
QString formattedLocation = QString("%1_%2_%3").arg(location.x).arg(location.y).arg(location.z);
// replace decimal . with '-'
formattedLocation.replace('.', '-');
QString username = AccountManager::getInstance().getAccountInfo().getUsername();
// normalize username, replace all non alphanumeric with '-'
username.replace(QRegExp("[^A-Za-z0-9_]"), "-");
QDateTime now = QDateTime::currentDateTime();
QString filename = FILENAME_PATH_FORMAT.arg(username, now.toString(DATETIME_FORMAT), formattedLocation);
const int IMAGE_QUALITY = 100;
if (!isTemporary) {
QString snapshotFullPath = Menu::getInstance()->getSnapshotsLocation();
if (!snapshotFullPath.endsWith(QDir::separator())) {
snapshotFullPath.append(QDir::separator());
}
snapshotFullPath.append(filename);
QFile* imageFile = new QFile(snapshotFullPath);
imageFile->open(QIODevice::WriteOnly);
shot.save(imageFile, 0, IMAGE_QUALITY);
imageFile->close();
return imageFile;
} else {
QTemporaryFile* imageTempFile = new QTemporaryFile(QDir::tempPath() + "/XXXXXX-" + filename);
if (!imageTempFile->open()) {
qDebug() << "Unable to open QTemporaryFile for temp snapshot. Will not save.";
return NULL;
}
shot.save(imageTempFile, 0, IMAGE_QUALITY);
imageTempFile->close();
return imageTempFile;
}
}
示例13: process
int process( const QDir &input, const QDir &output, const QString &xml )
{
QSqlDatabase database = QSqlDatabase::addDatabase( "QSQLITE" );
database.setDatabaseName( input.filePath( "speakers.db" ) );
if ( !database.open() ) {
qDebug() << "Failed to connect to database " << input.filePath( "speakers.db" );
return 3;
}
output.mkdir( "files.kde.org" );
QSqlQuery query( "SELECT * FROM speakers ORDER BY Id" );
QFile xmlFile( xml );
if ( !xmlFile.open( QFile::WriteOnly | QFile::Truncate ) ) {
qDebug() << "Failed to write to " << xmlFile.fileName();
return 3;
}
QTextStream xmlOut( &xmlFile );
xmlOut << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
xmlOut << "<!DOCTYPE knewstuff SYSTEM \"knewstuff.dtd\">\n";
xmlOut << "<?xml-stylesheet type=\"text/xsl\" href=\"speakers.xsl\" ?>\n";
xmlOut << "<knewstuff>\n";
int index = 71;
while (query.next()) {
QString const name = query.value(1).toString();
QString const email = query.value(2).toString();
QString const nick = query.value(3).toString();
QString const gender = query.value(4).toString();
QString const language = query.value(5).toString();
QString const lang = language.mid(0, language.indexOf(QLatin1Char('(')) - 1).replace(QLatin1Char(' '), QLatin1Char('-'));
QString const description = query.value(6).toString();
QString const token = query.value(7).toString();
QString const date = query.value(8).toString();
QString const zip = input.filePath( token );
QTemporaryFile tmpFile;
tmpFile.open();
QString const extracted = tmpFile.fileName();
tmpFile.remove();
QDir::root().mkdir( extracted );
qDebug() << "Name: " << name;
QString const simpleNick = QString( nick ).replace( QLatin1Char(' '), QLatin1Char('-') );
QString const nickDir = output.filePath("files.kde.org") + QLatin1Char('/') + simpleNick;
QDir::root().mkdir( nickDir );
extract( zip, extracted );
normalize( extracted );
createLegalFiles( extracted, name, email );
QFile::copy(extracted + QLatin1String("/Marble.ogg"), nickDir + QLatin1Char('/') + lang + QLatin1Char('-') + simpleNick + QLatin1String(".ogg"));
convertToMarbleFormat(extracted, nickDir + QLatin1Char('/') + lang + QLatin1Char('-') + simpleNick + QLatin1String(".zip"));
convertToTomTomFormat(extracted, nickDir, nick, simpleNick, index, gender == QLatin1String("male"), lang);
convertToNewStuffFormat(extracted, nickDir + QLatin1Char('/') + lang + QLatin1Char('-') + simpleNick + QLatin1String(".tar.gz"));
xmlOut << " <stuff category=\"marble/data/audio\">\n";
xmlOut << " <name lang=\"en\">" << language << " - " << nick << " (" << gender << ")" << "</name>\n";
xmlOut << " <author>" << name << "</author>\n";
xmlOut << " <licence>CC-By-SA 3.0</licence>\n";
xmlOut << " <summary lang=\"en\">" << description << "</summary>\n";
xmlOut << " <version>0.1</version>\n";
xmlOut << " <releasedate>" << date << "</releasedate>\n";
xmlOut << " <preview lang=\"en\">http://edu.kde.org/marble/speaker-" << gender << ".png</preview>\n";
xmlOut << " <payload lang=\"en\">http://files.kde.org/marble/audio/speakers/" << simpleNick << "/" << lang << "-" << simpleNick << ".tar.gz</payload>\n";
xmlOut << " <payload lang=\"ogg\">http://files.kde.org/marble/audio/speakers/" << simpleNick << "/" << lang << "-" << simpleNick << ".ogg</payload>\n";
xmlOut << " <payload lang=\"zip\">http://files.kde.org/marble/audio/speakers/" << simpleNick << "/" << lang << "-" << simpleNick << ".zip</payload>\n";
xmlOut << " <payload lang=\"tomtom\">http://files.kde.org/marble/audio/speakers/" << simpleNick << "/" << lang << "-" << simpleNick << "-TomTom.zip</payload>\n";
xmlOut << " </stuff>\n";
++index;
}
xmlOut << "</knewstuff>\n";
xmlFile.close();
return 0;
}
示例14: receivePackage
bool SharePlugin::receivePackage(const NetworkPackage& np)
{
/*
//TODO: Write a test like this
if (np.type() == PACKAGE_TYPE_PING) {
qCDebug(KDECONNECT_PLUGIN_SHARE) << "sending file" << (QDesktopServices::storageLocation(QDesktopServices::HomeLocation) + "/.bashrc");
NetworkPackage out(PACKAGE_TYPE_SHARE_REQUEST);
out.set("filename", mDestinationDir + "itworks.txt");
AutoClosingQFile* file = new AutoClosingQFile(QDesktopServices::storageLocation(QDesktopServices::HomeLocation) + "/.bashrc"); //Test file to transfer
out.setPayload(file, file->size());
device()->sendPackage(out);
return true;
}
*/
qCDebug(KDECONNECT_PLUGIN_SHARE) << "File transfer";
if (np.hasPayload()) {
//qCDebug(KDECONNECT_PLUGIN_SHARE) << "receiving file";
const QString filename = np.get<QString>(QStringLiteral("filename"), QString::number(QDateTime::currentMSecsSinceEpoch()));
const QUrl dir = destinationDir().adjusted(QUrl::StripTrailingSlash);
QUrl destination(dir.toString() + '/' + filename);
if (destination.isLocalFile() && QFile::exists(destination.toLocalFile())) {
destination = QUrl(dir.toString() + '/' + KIO::suggestName(dir, filename));
}
FileTransferJob* job = np.createPayloadTransferJob(destination);
job->setOriginName(device()->name() + ": " + filename);
connect(job, &KJob::result, this, &SharePlugin::finished);
KIO::getJobTracker()->registerJob(job);
job->start();
} else if (np.has(QStringLiteral("text"))) {
QString text = np.get<QString>(QStringLiteral("text"));
if (!QStandardPaths::findExecutable(QStringLiteral("kate")).isEmpty()) {
QProcess* proc = new QProcess();
connect(proc, SIGNAL(finished(int)), proc, SLOT(deleteLater()));
proc->start(QStringLiteral("kate"), QStringList(QStringLiteral("--stdin")));
proc->write(text.toUtf8());
proc->closeWriteChannel();
} else {
QTemporaryFile tmpFile;
tmpFile.setAutoRemove(false);
tmpFile.open();
tmpFile.write(text.toUtf8());
tmpFile.close();
const QUrl url = QUrl::fromLocalFile(tmpFile.fileName());
Q_EMIT shareReceived(url);
QDesktopServices::openUrl(url);
}
} else if (np.has(QStringLiteral("url"))) {
QUrl url = QUrl::fromEncoded(np.get<QByteArray>(QStringLiteral("url")));
QDesktopServices::openUrl(url);
Q_EMIT shareReceived(url);
} else {
qCDebug(KDECONNECT_PLUGIN_SHARE) << "Error: Nothing attached!";
}
return true;
}
示例15: generate
/**
* generate layout and apply it to the given diagram.
*
* @return true if generating succeeded
*/
bool LayoutGenerator::generate(UMLScene *scene, const QString &variant)
{
QTemporaryFile in;
QTemporaryFile out;
QTemporaryFile xdotOut;
if (!isEnabled()) {
uWarning() << "Could not apply autolayout because graphviz installation has not been found.";
return false;
}
#ifdef LAYOUTGENERATOR_DEBUG
in.setAutoRemove(false);
out.setAutoRemove(false);
xdotOut.setAutoRemove(false);
#endif
// generate filenames
in.open();
in.close();
out.open();
out.close();
xdotOut.open();
xdotOut.close();
#ifdef LAYOUTGENERATOR_DEBUG
qDebug() << textViewer() << in.fileName();
qDebug() << textViewer() << out.fileName();
qDebug() << textViewer() << xdotOut.fileName();
#endif
if (!createDotFile(scene, in.fileName(), variant))
return false;
QString executable = m_dotPath + QLatin1Char('/') + m_generator;
QProcess p;
QStringList args;
args << QLatin1String("-o") << out.fileName() << QLatin1String("-Tplain-ext") << in.fileName();
p.start(executable, args);
p.waitForFinished();
args.clear();
args << QLatin1String("-o") << xdotOut.fileName() << QLatin1String("-Txdot") << in.fileName();
p.start(executable, args);
p.waitForFinished();
#ifdef LAYOUTGENERATOR_DEBUG
QTemporaryFile pngFile;
pngFile.setAutoRemove(false);
pngFile.setFileTemplate(QDir::tempPath() + QLatin1String("/umbrello-layoutgenerator-XXXXXX.png"));
pngFile.open();
pngFile.close();
qDebug() << pngViewer() << pngFile.fileName();
args.clear();
args << QLatin1String("-o") << pngFile.fileName() << QLatin1String("-Tpng") << in.fileName();
p.start(executable, args);
p.waitForFinished();
#endif
#ifndef USE_XDOT
if (!readGeneratedDotFile(out.fileName()))
#else
if (!readGeneratedDotFile(xdotOut.fileName()))
#endif
return false;
return true;
}