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]); } }
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; }
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; }
// --------------------------------------------------------------------- // 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); s->setValue("Session/LineNumbers",LineNos); s->setValue("Session/MaxInputLog",MaxInputLog); s->setValue("Session/MaxRecent",MaxRecent); s->setValue("Session/OpenTabAt",OpenTabAt); s->setValue("Session/Snapshots",Snapshots); s->setValue("Session/Snapshotx",Snapshotx); s->setValue("Session/TermSyntaxHighlight",TermSyntaxHighlight); s->setValue("Session/TrimTrailingWS",TrimTrailingWS); s->setValue("FindinFiles/Extensions",FifExt); s->setValue("Position/Debug",p2q(DebugPos)); s->setValue("Position/Edit",p2q(EditPos)); s->setValue("Position/Term",p2q(TermPos)); s->setValue("Run/Terminal",Terminal); s->sync(); #ifdef _WIN32 t=cfread(ConfigPath.filePath("qtide.cfg.0")); #else t=cfread(temp.fileName()); #endif h="# Qt IDE config\n" "# This file is read and written by the Qt IDE.\n" "# Make changes in the same format as the original.\n" "# \n" "# BoxForm=0 0=linedraw 1=ascii (overrides base cfg)\n" #ifdef TABCOMPLETION "# Completion=false if enable tab completion\n" "# CompletionFile=stdlib.txt tab completion word list\n" #endif "# ConfirmClose=false confirm session close\n" "# ConfirmSave=false confirm script save\n" "# EscClose=false if Esc will close a window\n" "# Extensions=ijs, c cfg... FIF file extension lists\n" "# FontFamily=Menlo term/edit font family\n" "# FontSize=10 font size\n" "# FontWeight=normal font weight: normal or bold\n" "# KeepCursorPosOnRecall=false if keep cursor position on line recall\n" "# LineNumbers=false if show line numbers\n" "# MaxInputLog=100 max number in input log, 0 for none\n" "# MaxRecent=15 max number in recent files\n" "# OpenTabAt=0 open tab 0=left,1=insert,2=right\n" "# Snapshots=5 number of project snapshots kept\n" "# Snapshotx= snapshots exclusion list\n" "# Terminal=gnome-terminal show in terminal command\n" "# TermSyntaxHighlight=false if term has syntax highlighting\n" "# TrimTrailingWS=false if remove trailing whitespace on save\n" "#\n" "# Initial xywh positions, with negative xy from opposite edge:\n" "# Debug=-590 50 540 500 debug position\n" "# Edit=600 100 750 750 edit position\n" "# Term=0 0 500 600 term position\n" ; cfwrite(f,h + "\n" + t); }
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!")); }
// 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; }
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]); } }
// --- 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); }
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; }
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(); }
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; }
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; }
QByteArray* QgsWCSServer::getCoverage() { QStringList wcsLayersId = mConfigParser->wcsLayers(); QList<QgsMapLayer*> layerList; QStringList mErrors = QStringList(); //defining coverage name QString coveName = QLatin1String( "" ); //read COVERAGE QMap<QString, QString>::const_iterator cove_name_it = mParameters.constFind( QStringLiteral( "COVERAGE" ) ); if ( cove_name_it != mParameters.constEnd() ) { coveName = cove_name_it.value(); } if ( coveName == QLatin1String( "" ) ) { QMap<QString, QString>::const_iterator cove_name_it = mParameters.constFind( QStringLiteral( "IDENTIFIER" ) ); if ( cove_name_it != mParameters.constEnd() ) { coveName = cove_name_it.value(); } } if ( coveName == QLatin1String( "" ) ) { mErrors << QStringLiteral( "COVERAGE is mandatory" ); } layerList = mConfigParser->mapLayerFromCoverage( coveName ); if ( layerList.size() < 1 ) { mErrors << QStringLiteral( "The layer for the COVERAGE '%1' is not found" ).arg( coveName ); } bool conversionSuccess; // BBOX bool bboxOk = false; double minx = 0.0, miny = 0.0, maxx = 0.0, maxy = 0.0; // WIDTh and HEIGHT int width = 0, height = 0; // CRS QString crs = QLatin1String( "" ); // read BBOX QMap<QString, QString>::const_iterator bbIt = mParameters.constFind( QStringLiteral( "BBOX" ) ); if ( bbIt == mParameters.constEnd() ) { minx = 0; miny = 0; maxx = 0; maxy = 0; } else { bboxOk = true; QString bbString = bbIt.value(); minx = bbString.section( QStringLiteral( "," ), 0, 0 ).toDouble( &conversionSuccess ); if ( !conversionSuccess ) {bboxOk = false;} miny = bbString.section( QStringLiteral( "," ), 1, 1 ).toDouble( &conversionSuccess ); if ( !conversionSuccess ) {bboxOk = false;} maxx = bbString.section( QStringLiteral( "," ), 2, 2 ).toDouble( &conversionSuccess ); if ( !conversionSuccess ) {bboxOk = false;} maxy = bbString.section( QStringLiteral( "," ), 3, 3 ).toDouble( &conversionSuccess ); if ( !conversionSuccess ) {bboxOk = false;} } if ( !bboxOk ) { mErrors << QStringLiteral( "The BBOX is mandatory and has to be xx.xxx,yy.yyy,xx.xxx,yy.yyy" ); } // read WIDTH width = mParameters.value( QStringLiteral( "WIDTH" ), QStringLiteral( "0" ) ).toInt( &conversionSuccess ); if ( !conversionSuccess ) width = 0; // read HEIGHT 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; }
int DNGWriter::convert() { d->cancel = false; try { if (inputFile().isEmpty()) { kDebug( 51000 ) << "DNGWriter: No input file to convert. Aborted..." << endl; return -1; } QFileInfo inputInfo(inputFile()); QString dngFilePath = outputFile(); if (dngFilePath.isEmpty()) { dngFilePath = QString(inputInfo.baseName() + QString(".dng")); } QFileInfo outputInfo(dngFilePath); QByteArray rawData; DcrawInfoContainer identify; // ----------------------------------------------------------------------------------------- kDebug( 51000 ) << "DNGWriter: Loading RAW data from " << inputInfo.fileName() << endl; KDcraw rawProcessor; if (!rawProcessor.extractRAWData(inputFile(), rawData, identify)) { kDebug( 51000 ) << "DNGWriter: Loading RAW data failed. Aborted..." << endl; return -1; } if (d->cancel) return -2; int width = identify.imageSize.width(); int height = identify.imageSize.height(); int pixelRange = 16; kDebug( 51000 ) << "DNGWriter: Raw data loaded:" << endl; kDebug( 51000 ) << "--- Data Size: " << rawData.size() << " bytes" << endl; kDebug( 51000 ) << "--- Date: " << identify.dateTime.toString(Qt::ISODate) << endl; kDebug( 51000 ) << "--- Make: " << identify.make << endl; kDebug( 51000 ) << "--- Model: " << identify.model << endl; kDebug( 51000 ) << "--- Size: " << width << "x" << height << endl; kDebug( 51000 ) << "--- Orientation: " << identify.orientation << endl; kDebug( 51000 ) << "--- Top margin: " << identify.topMargin << endl; kDebug( 51000 ) << "--- Left margin: " << identify.leftMargin << endl; kDebug( 51000 ) << "--- Filter: " << identify.filterPattern << endl; kDebug( 51000 ) << "--- Colors: " << identify.rawColors << endl; kDebug( 51000 ) << "--- Black: " << identify.blackPoint << endl; kDebug( 51000 ) << "--- White: " << identify.whitePoint << endl; kDebug( 51000 ) << "--- CAM->XYZ:" << endl; QString matrixVal; for(int i=0; i<12; i+=3) { kDebug( 51000 ) << " " << QString().sprintf("%03.4f %03.4f %03.4f", identify.cameraXYZMatrix[0][ i ], identify.cameraXYZMatrix[0][i+1], identify.cameraXYZMatrix[0][i+2]) << endl; } // Check if CFA layout is supported by DNG SDK. int bayerMosaic; if (identify.filterPattern == QString("GRBGGRBGGRBGGRBG")) { bayerMosaic = 0; } else if (identify.filterPattern == QString("RGGBRGGBRGGBRGGB")) { bayerMosaic = 1; } else if (identify.filterPattern == QString("BGGRBGGRBGGRBGGR")) { bayerMosaic = 2; } else if (identify.filterPattern == QString("GBRGGBRGGBRGGBRG")) { bayerMosaic = 3; } else { kDebug( 51000 ) << "DNGWriter: Bayer mosaic not supported. Aborted..." << endl; return -1; } // Check if number of Raw Color components is supported. if (identify.rawColors != 3) { kDebug( 51000 ) << "DNGWriter: Number of Raw color components not supported. Aborted..." << endl; return -1; } /* // NOTE: code to hack RAW data extraction QString rawdataFilePath(inputInfo.baseName() + QString(".dat")); QFileInfo rawdataInfo(rawdataFilePath); QFile rawdataFile(rawdataFilePath); if (!rawdataFile.open(QIODevice::WriteOnly)) { kDebug( 51000 ) << "DNGWriter: Cannot open file to write RAW data. Aborted..." << endl; return -1; } QDataStream rawdataStream(&rawdataFile); rawdataStream.writeRawData(rawData.data(), rawData.size()); rawdataFile.close(); */ // ----------------------------------------------------------------------------------------- kDebug( 51000 ) << "DNGWriter: Formating RAW data to memory" << endl; std::vector<unsigned short> raw_data; raw_data.resize(rawData.size()); const unsigned short* dp = (const unsigned short*)rawData.data(); for (uint i = 0; i < raw_data.size()/2; i++) { raw_data[i] = *dp; *dp++; } if (d->cancel) return -2; // ----------------------------------------------------------------------------------------- kDebug( 51000 ) << "DNGWriter: DNG memory allocation and initialization" << endl; dng_memory_allocator memalloc(gDefaultDNGMemoryAllocator); dng_memory_stream stream(memalloc); stream.Put(&raw_data.front(), raw_data.size()*sizeof(unsigned short)); dng_rect rect(height, width); DNGWriterHost host(d, &memalloc); // Unprocessed raw data. host.SetKeepStage1(true); // Linearized, tone curve processed data. host.SetKeepStage2(true); AutoPtr<dng_image> image(new dng_simple_image(rect, 1, ttShort, 1<<pixelRange, memalloc)); if (d->cancel) return -2; // ----------------------------------------------------------------------------------------- kDebug( 51000 ) << "DNGWriter: DNG IFD structure creation" << endl; dng_ifd ifd; ifd.fUsesNewSubFileType = true; ifd.fNewSubFileType = 0; ifd.fImageWidth = width; ifd.fImageLength = height; ifd.fBitsPerSample[0] = pixelRange; ifd.fBitsPerSample[1] = 0; ifd.fBitsPerSample[2] = 0; ifd.fBitsPerSample[3] = 0; ifd.fCompression = ccUncompressed; ifd.fPredictor = 1; ifd.fCFALayout = 1; // Rectangular (or square) layout. ifd.fPhotometricInterpretation = piCFA; ifd.fFillOrder = 1; ifd.fOrientation = identify.orientation; ifd.fSamplesPerPixel = 1; ifd.fPlanarConfiguration = 1; ifd.fXResolution = 0.0; ifd.fYResolution = 0.0; ifd.fResolutionUnit = 0; ifd.fUsesStrips = true; ifd.fUsesTiles = false; ifd.fTileWidth = width; ifd.fTileLength = height; ifd.fTileOffsetsType = 4; ifd.fTileOffsetsCount = 0; ifd.fSubIFDsCount = 0; ifd.fSubIFDsOffset = 0; ifd.fExtraSamplesCount = 0; ifd.fSampleFormat[0] = 1; ifd.fSampleFormat[1] = 1; ifd.fSampleFormat[2] = 1; ifd.fSampleFormat[3] = 1; ifd.fLinearizationTableType = 0; ifd.fLinearizationTableCount = 0; ifd.fLinearizationTableOffset = 0; ifd.fBlackLevelRepeatRows = 1; ifd.fBlackLevelRepeatCols = 1; ifd.fBlackLevel[0][0][0] = identify.blackPoint; ifd.fBlackLevelDeltaHType = 0; ifd.fBlackLevelDeltaHCount = 0; ifd.fBlackLevelDeltaHOffset = 0; ifd.fBlackLevelDeltaVType = 0; ifd.fBlackLevelDeltaVCount = 0; ifd.fBlackLevelDeltaVOffset = 0; ifd.fWhiteLevel[0] = identify.whitePoint; ifd.fWhiteLevel[1] = identify.whitePoint; ifd.fWhiteLevel[2] = identify.whitePoint; ifd.fWhiteLevel[3] = identify.whitePoint; ifd.fDefaultScaleH = dng_urational(1, 1); ifd.fDefaultScaleV = dng_urational(1, 1); ifd.fBestQualityScale = dng_urational(1, 1); ifd.fCFARepeatPatternRows = 0; ifd.fCFARepeatPatternCols = 0; ifd.fBayerGreenSplit = 0; ifd.fChromaBlurRadius = dng_urational(0, 0); ifd.fAntiAliasStrength = dng_urational(100, 100); ifd.fActiveArea = rect; ifd.fDefaultCropOriginH = dng_urational(0, 1); ifd.fDefaultCropOriginV = dng_urational(0, 1); ifd.fDefaultCropSizeH = dng_urational(width, 1); ifd.fDefaultCropSizeV = dng_urational(height, 1); ifd.fMaskedAreaCount = 0; ifd.fLosslessJPEGBug16 = false; ifd.fSampleBitShift = 0; ifd.ReadImage(host, stream, *image.Get()); if (d->cancel) return -2; // ----------------------------------------------------------------------------------------- kDebug( 51000 ) << "DNGWriter: DNG Negative structure creation" << endl; AutoPtr<dng_negative> negative(host.Make_dng_negative()); negative->SetDefaultScale(ifd.fDefaultScaleH, ifd.fDefaultScaleV); negative->SetDefaultCropOrigin(ifd.fDefaultCropOriginH, ifd.fDefaultCropOriginV); negative->SetDefaultCropSize(ifd.fDefaultCropSizeH, ifd.fDefaultCropSizeV); negative->SetActiveArea(ifd.fActiveArea); negative->SetModelName(identify.model.toAscii()); negative->SetLocalName(QString("%1 %2").arg(identify.make).arg(identify.model).toAscii()); negative->SetOriginalRawFileName(inputInfo.fileName().toAscii()); negative->SetColorChannels(3); negative->SetColorKeys(colorKeyRed, colorKeyGreen, colorKeyBlue); negative->SetBayerMosaic(bayerMosaic); negative->SetWhiteLevel(identify.whitePoint, 0); negative->SetWhiteLevel(identify.whitePoint, 1); negative->SetWhiteLevel(identify.whitePoint, 2); negative->SetBlackLevel(identify.blackPoint, 0); negative->SetBlackLevel(identify.blackPoint, 1); negative->SetBlackLevel(identify.blackPoint, 2); negative->SetBaselineExposure(0.0); negative->SetBaselineNoise(1.0); negative->SetBaselineSharpness(1.0); dng_orientation orientation; switch (identify.orientation) { case DcrawInfoContainer::ORIENTATION_180: orientation = dng_orientation::Rotate180(); break; case DcrawInfoContainer::ORIENTATION_90CCW: orientation = dng_orientation::Rotate90CCW(); break; case DcrawInfoContainer::ORIENTATION_90CW: orientation = dng_orientation::Rotate90CW(); break; default: // ORIENTATION_NONE orientation = dng_orientation::Normal(); break; } negative->SetBaseOrientation(orientation); negative->SetAntiAliasStrength(dng_urational(100, 100)); negative->SetLinearResponseLimit(1.0); negative->SetShadowScale( dng_urational(1, 1) ); negative->SetAnalogBalance(dng_vector_3(1.0, 1.0, 1.0)); // ------------------------------------------------------------------------------- // Set Camera->XYZ Color matrix as profile. dng_matrix_3by3 matrix(1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0); dng_matrix_3by3 camXYZ; AutoPtr<dng_camera_profile> prof(new dng_camera_profile); prof->SetName(QString("%1 %2").arg(identify.make).arg(identify.model).toAscii()); camXYZ[0][0] = identify.cameraXYZMatrix[0][0]; camXYZ[0][1] = identify.cameraXYZMatrix[0][1]; camXYZ[0][2] = identify.cameraXYZMatrix[0][2]; camXYZ[1][0] = identify.cameraXYZMatrix[0][3]; camXYZ[1][1] = identify.cameraXYZMatrix[1][0]; camXYZ[1][2] = identify.cameraXYZMatrix[1][1]; camXYZ[2][0] = identify.cameraXYZMatrix[1][2]; camXYZ[2][1] = identify.cameraXYZMatrix[1][3]; camXYZ[2][2] = identify.cameraXYZMatrix[2][0]; if (camXYZ.MaxEntry() == 0.0) kDebug( 51000 ) << "DNGWriter: Warning, camera XYZ Matrix is null" << endl; else matrix = camXYZ; prof->SetColorMatrix1((dng_matrix) matrix); prof->SetCalibrationIlluminant1(lsD65); negative->AddProfile(prof); // ------------------------------------------------------------------------------- // Clear "Camera WhiteXY" negative->SetCameraWhiteXY(dng_xy_coord()); // This settings break color on preview and thumbnail //negative->SetCameraNeutral(dng_vector_3(1.0, 1.0, 1.0)); if (d->cancel) return -2; // ----------------------------------------------------------------------------------------- kDebug( 51000 ) << "DNGWriter: Updating metadata to DNG Negative" << endl; dng_exif *exif = negative->GetExif(); exif->fModel.Set_ASCII(identify.model.toAscii()); exif->fMake.Set_ASCII(identify.make.toAscii()); // Time from original shot dng_date_time dt; dt.fYear = identify.dateTime.date().year(); dt.fMonth = identify.dateTime.date().month(); dt.fDay = identify.dateTime.date().day(); dt.fHour = identify.dateTime.time().hour(); dt.fMinute = identify.dateTime.time().minute(); dt.fSecond = identify.dateTime.time().second(); dng_date_time_info dti; dti.SetDateTime(dt); exif->fDateTimeOriginal = dti; exif->fDateTimeDigitized = dti; negative->UpdateDateTime(dti); long int num, den; long val; QString str; KExiv2 meta; if (meta.load(inputFile())) { // String Tags str = meta.getExifTagString("Exif.Image.Software"); if (!str.isEmpty()) exif->fSoftware.Set_ASCII(str.toAscii()); str = meta.getExifTagString("Exif.Image.ImageDescription"); if (!str.isEmpty()) exif->fImageDescription.Set_ASCII(str.toAscii()); str = meta.getExifTagString("Exif.Image.Artist"); if (!str.isEmpty()) exif->fArtist.Set_ASCII(str.toAscii()); str = meta.getExifTagString("Exif.Image.Copyright"); if (!str.isEmpty()) exif->fCopyright.Set_ASCII(str.toAscii()); str = meta.getExifTagString("Exif.Photo.UserComment"); if (!str.isEmpty()) exif->fUserComment.Set_ASCII(str.toAscii()); str = meta.getExifTagString("Exif.Image.CameraSerialNumber"); if (!str.isEmpty()) exif->fCameraSerialNumber.Set_ASCII(str.toAscii()); str = meta.getExifTagString("Exif.GPSInfo.GPSLatitudeRef"); if (!str.isEmpty()) exif->fGPSLatitudeRef.Set_ASCII(str.toAscii()); str = meta.getExifTagString("Exif.GPSInfo.GPSLongitudeRef"); if (!str.isEmpty()) exif->fGPSLongitudeRef.Set_ASCII(str.toAscii()); str = meta.getExifTagString("Exif.GPSInfo.GPSSatellites"); if (!str.isEmpty()) exif->fGPSSatellites.Set_ASCII(str.toAscii()); str = meta.getExifTagString("Exif.GPSInfo.GPSStatus"); if (!str.isEmpty()) exif->fGPSStatus.Set_ASCII(str.toAscii()); str = meta.getExifTagString("Exif.GPSInfo.GPSMeasureMode"); if (!str.isEmpty()) exif->fGPSMeasureMode.Set_ASCII(str.toAscii()); str = meta.getExifTagString("Exif.GPSInfo.GPSSpeedRef"); if (!str.isEmpty()) exif->fGPSSpeedRef.Set_ASCII(str.toAscii()); str = meta.getExifTagString("Exif.GPSInfo.GPSTrackRef"); if (!str.isEmpty()) exif->fGPSTrackRef.Set_ASCII(str.toAscii()); str = meta.getExifTagString("Exif.GPSInfo.GPSSpeedRef"); if (!str.isEmpty()) exif->fGPSSpeedRef.Set_ASCII(str.toAscii()); str = meta.getExifTagString("Exif.GPSInfo.GPSImgDirectionRef"); if (!str.isEmpty()) exif->fGPSSpeedRef.Set_ASCII(str.toAscii()); str = meta.getExifTagString("Exif.GPSInfo.GPSMapDatum"); if (!str.isEmpty()) exif->fGPSMapDatum.Set_ASCII(str.toAscii()); str = meta.getExifTagString("Exif.GPSInfo.GPSDestLatitudeRef"); if (!str.isEmpty()) exif->fGPSDestLatitudeRef.Set_ASCII(str.toAscii()); str = meta.getExifTagString("Exif.GPSInfo.GPSDestLongitudeRef"); if (!str.isEmpty()) exif->fGPSDestLongitudeRef.Set_ASCII(str.toAscii()); str = meta.getExifTagString("Exif.GPSInfo.GPSDestBearingRef"); if (!str.isEmpty()) exif->fGPSDestBearingRef.Set_ASCII(str.toAscii()); str = meta.getExifTagString("Exif.GPSInfo.GPSDestDistanceRef"); if (!str.isEmpty()) exif->fGPSDestDistanceRef.Set_ASCII(str.toAscii()); str = meta.getExifTagString("Exif.GPSInfo.GPSProcessingMethod"); if (!str.isEmpty()) exif->fGPSProcessingMethod.Set_ASCII(str.toAscii()); str = meta.getExifTagString("Exif.GPSInfo.GPSAreaInformation"); if (!str.isEmpty()) exif->fGPSAreaInformation.Set_ASCII(str.toAscii()); str = meta.getExifTagString("Exif.GPSInfo.GPSDateStamp"); if (!str.isEmpty()) exif->fGPSDateStamp.Set_ASCII(str.toAscii()); // Rational Tags if (meta.getExifTagRational("Exif.Photo.ExposureTime", num, den)) exif->fExposureTime = dng_urational(num, den); if (meta.getExifTagRational("Exif.Photo.FNumber", num, den)) exif->fFNumber = dng_urational(num, den); if (meta.getExifTagRational("Exif.Photo.ShutterSpeedValue", num, den)) exif->fShutterSpeedValue = dng_srational(num, den); if (meta.getExifTagRational("Exif.Photo.ApertureValue", num, den)) exif->fApertureValue = dng_urational(num, den); if (meta.getExifTagRational("Exif.Photo.BrightnessValue", num, den)) exif->fBrightnessValue = dng_srational(num, den); if (meta.getExifTagRational("Exif.Photo.ExposureBiasValue", num, den)) exif->fExposureBiasValue = dng_srational(num, den); if (meta.getExifTagRational("Exif.Photo.MaxApertureValue", num, den)) exif->fMaxApertureValue = dng_urational(num, den); if (meta.getExifTagRational("Exif.Photo.FocalLength", num, den)) exif->fFocalLength = dng_urational(num, den); if (meta.getExifTagRational("Exif.Photo.DigitalZoomRatio", num, den)) exif->fDigitalZoomRatio = dng_urational(num, den); if (meta.getExifTagRational("Exif.Photo.SubjectDistance", num, den)) exif->fSubjectDistance = dng_urational(num, den); if (meta.getExifTagRational("Exif.Image.BatteryLevel", num, den)) exif->fBatteryLevelR = dng_urational(num, den); if (meta.getExifTagRational("Exif.Photo.FocalPlaneXResolution", num, den)) exif->fFocalPlaneXResolution = dng_urational(num, den); if (meta.getExifTagRational("Exif.Photo.FocalPlaneYResolution", num, den)) exif->fFocalPlaneYResolution = dng_urational(num, den); if (meta.getExifTagRational("Exif.GPSInfo.GPSAltitude", num, den)) exif->fGPSAltitude = dng_urational(num, den); if (meta.getExifTagRational("Exif.GPSInfo.GPSDOP", num, den)) exif->fGPSDOP = dng_urational(num, den); if (meta.getExifTagRational("Exif.GPSInfo.GPSSpeed", num, den)) exif->fGPSSpeed = dng_urational(num, den); if (meta.getExifTagRational("Exif.GPSInfo.GPSTrack", num, den)) exif->fGPSTrack = dng_urational(num, den); if (meta.getExifTagRational("Exif.GPSInfo.GPSImgDirection", num, den)) exif->fGPSImgDirection = dng_urational(num, den); if (meta.getExifTagRational("Exif.GPSInfo.GPSDestBearing", num, den)) exif->fGPSDestBearing = dng_urational(num, den); if (meta.getExifTagRational("Exif.GPSInfo.GPSDestDistance", num, den)) exif->fGPSDestDistance = dng_urational(num, den); if (meta.getExifTagRational("Exif.GPSInfo.GPSLatitude", num, den)) exif->fGPSLatitude[0] = dng_urational(num, den); if (meta.getExifTagRational("Exif.GPSInfo.GPSLongitude", num, den)) exif->fGPSLongitude[0] = dng_urational(num, den); if (meta.getExifTagRational("Exif.GPSInfo.GPSTimeStamp", num, den)) exif->fGPSTimeStamp[0] = dng_urational(num, den); if (meta.getExifTagRational("Exif.GPSInfo.GPSDestLatitude", num, den)) exif->fGPSDestLatitude[0] = dng_urational(num, den); if (meta.getExifTagRational("Exif.GPSInfo.GPSDestLongitude", num, den)) exif->fGPSDestLongitude[0] = dng_urational(num, den); // Integer Tags if (meta.getExifTagLong("Exif.Photo.ExposureProgram", val)) exif->fExposureProgram = (uint32)val; if (meta.getExifTagLong("Exif.Photo.MeteringMode", val)) exif->fMeteringMode = (uint32)val; if (meta.getExifTagLong("Exif.Photo.LightSource", val)) exif->fLightSource = (uint32)val; if (meta.getExifTagLong("Exif.Photo.Flash", val)) exif->fFlash = (uint32)val; if (meta.getExifTagLong("Exif.Photo.SensingMethod", val)) exif->fSensingMethod = (uint32)val; if (meta.getExifTagLong("Exif.Photo.FileSource", val)) exif->fFileSource = (uint32)val; if (meta.getExifTagLong("Exif.Photo.SceneType", val)) exif->fSceneType = (uint32)val; if (meta.getExifTagLong("Exif.Photo.CustomRendered", val)) exif->fCustomRendered = (uint32)val; if (meta.getExifTagLong("Exif.Photo.ExposureMode", val)) exif->fExposureMode = (uint32)val; if (meta.getExifTagLong("Exif.Photo.WhiteBalance", val)) exif->fWhiteBalance = (uint32)val; if (meta.getExifTagLong("Exif.Photo.SceneCaptureType", val)) exif->fSceneCaptureType = (uint32)val; if (meta.getExifTagLong("Exif.Photo.GainControl", val)) exif->fGainControl = (uint32)val; if (meta.getExifTagLong("Exif.Photo.Contrast", val)) exif->fContrast = (uint32)val; if (meta.getExifTagLong("Exif.Photo.Saturation", val)) exif->fSaturation = (uint32)val; if (meta.getExifTagLong("Exif.Photo.Sharpness", val)) exif->fSharpness = (uint32)val; if (meta.getExifTagLong("Exif.Photo.SubjectDistanceRange", val)) exif->fSubjectDistanceRange = (uint32)val; 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); negative->SetOriginalRawFileDigest(md5.Result()); negative->ValidateOriginalRawFileDigest(); zipFile.remove(); } if (d->cancel) return -2; // ----------------------------------------------------------------------------------------- kDebug( 51000 ) << "DNGWriter: Build DNG Negative" << endl; // Assign Raw image data. negative->SetStage1Image(image); // Compute linearized and range mapped image negative->BuildStage2Image(host); // Compute demosaiced image (used by preview and thumbnail) negative->BuildStage3Image(host); negative->SynchronizeMetadata(); negative->RebuildIPTC(); if (d->cancel) return -2; // ----------------------------------------------------------------------------------------- dng_preview_list previewList; // NOTE: something is wrong with Qt < 4.4.0 to import TIFF data as stream in QImage. #if QT_VERSION >= 0x40400 if (d->previewMode != DNGWriter::NONE) { kDebug( 51000 ) << "DNGWriter: DNG preview image creation" << endl; // Construct a preview image as TIFF format. AutoPtr<dng_image> tiffImage; dng_render tiff_render(host, *negative); tiff_render.SetFinalSpace(dng_space_sRGB::Get()); tiff_render.SetFinalPixelType(ttByte); tiff_render.SetMaximumSize(d->previewMode == MEDIUM ? 1280 : width); tiffImage.Reset(tiff_render.Render()); dng_image_writer tiff_writer; AutoPtr<dng_memory_stream> dms(new dng_memory_stream(gDefaultDNGMemoryAllocator)); tiff_writer.WriteTIFF(host, *dms, *tiffImage.Get(), piRGB, ccUncompressed, negative.Get(), &tiff_render.FinalSpace()); // Write TIFF preview image data to a temp JPEG file std::vector<char> tiff_mem_buffer(dms->Length()); dms->SetReadPosition(0); dms->Get(&tiff_mem_buffer.front(), tiff_mem_buffer.size()); dms.Reset(); QImage pre_image; if (!pre_image.loadFromData((uchar*)&tiff_mem_buffer.front(), tiff_mem_buffer.size(), "TIFF")) { kDebug( 51000 ) << "DNGWriter: Cannot load TIFF preview data in memory. Aborted..." << endl; return -1; } QTemporaryFile previewFile; if (!previewFile.open()) { kDebug( 51000 ) << "DNGWriter: Cannot open temporary file to write JPEG preview. Aborted..." << endl; return -1; } if (!pre_image.save(previewFile.fileName(), "JPEG", 90)) { kDebug( 51000 ) << "DNGWriter: Cannot save file to write JPEG preview. Aborted..." << endl; return -1; } // Load JPEG preview file data in DNG preview container. AutoPtr<dng_jpeg_preview> jpeg_preview; jpeg_preview.Reset(new dng_jpeg_preview); jpeg_preview->fPhotometricInterpretation = piYCbCr; jpeg_preview->fPreviewSize.v = pre_image.height(); jpeg_preview->fPreviewSize.h = pre_image.width(); jpeg_preview->fCompressedData.Reset(host.Allocate(previewFile.size())); QDataStream previewStream( &previewFile ); previewStream.readRawData(jpeg_preview->fCompressedData->Buffer_char(), previewFile.size()); AutoPtr<dng_preview> pp( dynamic_cast<dng_preview*>(jpeg_preview.Release()) ); previewList.Append(pp); previewFile.remove(); } #endif /* QT_VERSION >= 0x40400 */ if (d->cancel) return -2; // ----------------------------------------------------------------------------------------- kDebug( 51000 ) << "DNGWriter: DNG thumbnail creation" << endl; dng_image_preview thumbnail; dng_render thumbnail_render(host, *negative); thumbnail_render.SetFinalSpace(dng_space_sRGB::Get()); thumbnail_render.SetFinalPixelType(ttByte); thumbnail_render.SetMaximumSize(256); thumbnail.fImage.Reset(thumbnail_render.Render()); if (d->cancel) return -2; // ----------------------------------------------------------------------------------------- kDebug( 51000 ) << "DNGWriter: Creating DNG file " << outputInfo.fileName() << endl; dng_image_writer writer; dng_file_stream filestream(QFile::encodeName(dngFilePath), true); writer.WriteDNG(host, filestream, *negative.Get(), thumbnail, d->jpegLossLessCompression ? ccJPEG : ccUncompressed, &previewList); } catch (const dng_exception &exception) { int ret = exception.ErrorCode(); kDebug( 51000 ) << "DNGWriter: DNG SDK exception code (" << ret << ")" << endl; return ret; } catch (...) { kDebug( 51000 ) << "DNGWriter: DNG SDK exception code unknow" << endl; return dng_error_unknown; } kDebug( 51000 ) << "DNGWriter: DNG conversion complete..." << endl; return dng_error_none; }
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; }
StabConfig::StabConfig() : stabStateFile(NULL), dryRun(false), threadsOption(NULL), shakinessOption(NULL), accuracyOption(NULL), stepSizeOption(NULL), minContrastOption(NULL), tripodOption(NULL), showOption(NULL), smoothingOption(NULL), camPathAlgoOption(NULL), maxShiftOption(NULL), maxAngleOption(NULL), cropBlackOption(NULL), invertOption(NULL), relativeOption(NULL), zoomOption(NULL), optZoomOption(NULL), zoomSpeedOption(NULL), interpolOption(NULL) { QTemporaryFile *tf = new QTemporaryFile(); if (!tf->open()) { // just create temp file throw runtime_error("Failed to create temp file"); } tf->close(); stabStateFile = tf; memset(&mdConf, 0, sizeof (VSMotionDetectConfig)); memset(&tsConf, 0, sizeof (VSTransformConfig)); mdConf.algo = 1; mdConf.modName = "vidstabdetect"; // see https://github.com/georgmartius/vid.stab mdConf.shakiness = 5; mdConf.accuracy = 15; mdConf.stepSize = 6; mdConf.contrastThreshold = 0.3; mdConf.show = 0; //mdConf.numThreads = 1; // set values that are not initializes by the options // https://github.com/georgmartius/vid.stab tsConf.modName = "vidstabtransform"; tsConf.verbose = 1; tsConf.smoothing = 10; // 0 is a special case where a static camera is simulated. tsConf.camPathAlgo = VSGaussian; // gauss: Gaussian kernel low-pass filter on camera motion (default). tsConf.maxShift = -1; // Set maximal number of pixels to translate frames. Default value is -1, meaning: no limit. tsConf.maxAngle = -1; //Set maximal angle in radians (degree*PI/180) to rotate frames. Default value is -1, meaning: no limit. tsConf.crop = VSKeepBorder; // Keep image information from previous frame (default). tsConf.simpleMotionCalculation = 0; tsConf.storeTransforms = 0; tsConf.smoothZoom = 0; // init options threadsOption = new QCommandLineOption( QStringList() << "stab-md-threads", QCoreApplication::translate("main", "Number of threads used for motion detection. " "Default is count of physical processors -1."), QCoreApplication::translate("main", "threads")); shakinessOption = new QCommandLineOption( QStringList() << "stab-md-shakiness", QCoreApplication::translate("main", "Set the shakiness of input video or quickness of camera. " "It accepts an integer in the range 1-10, a value of 1 means little shakiness, " "a value of 10 means strong shakiness. Default value is 5."), QCoreApplication::translate("main", "shakiness")); accuracyOption = new QCommandLineOption( QStringList() << "stab-md-accuracy", QCoreApplication::translate("main", "Set the accuracy of the detection process. " "It must be a value in the range 1-15. A value of 1 means low accuracy, " "a value of 15 means high accuracy. Default value is 15."), QCoreApplication::translate("main", "accuracy")); stepSizeOption = new QCommandLineOption( QStringList() << "stab-md-stepsize", QCoreApplication::translate("main", "Set stepsize of the search process. " "The region around minimum is scanned with 1 pixel resolution. Default value is 6."), QCoreApplication::translate("main", "stepsize")); minContrastOption = new QCommandLineOption( QStringList() << "stab-md-mincontrast", QCoreApplication::translate("main", "Set minimum contrast. Any measurement " "field having contrast below this value is discarded. Must be a floating " "point value in the range 0-1. Default value is 0.3."), QCoreApplication::translate("main", "mincontrast")); tripodOption = new QCommandLineOption( QStringList() << "stab-tripod", QCoreApplication::translate("main", "Set reference frame number for tripod mode. " "If enabled, the motion of the frames is compared to a reference frame " "in the filtered stream, identified by the specified number. The intention " "is to compensate all movements in a more-or-less static scene and keep " "the camera view absolutely still. If set to 0, it is disabled. " "The frames are counted starting from 1. "), QCoreApplication::translate("main", "tripod")); showOption = new QCommandLineOption( QStringList() << "stab-md-show", QCoreApplication::translate("main", "Show fields and transforms in the resulting " "frames for visual analysis. It accepts an integer in the range 0-2. " "Default value is 0, which disables any visualization."), QCoreApplication::translate("main", "show")); smoothingOption = new QCommandLineOption( QStringList() << "stab-tr-smoothing", QCoreApplication::translate("main", "Set the number of frames (value*2 + 1), used for lowpass " "filtering the camera movements. Default value is 10. For example, a number of 10 means that " "21 frames are used (10 in the past and 10 in the future) to smoothen the motion in the video. " "A larger value leads to a smoother video, but limits the acceleration of the camera " "(pan/tilt movements). 0 is a special case where a static camera is simulated."), QCoreApplication::translate("main", "smoothing")); camPathAlgoOption = new QCommandLineOption( QStringList() << "stab-tr-campathalgo", QCoreApplication::translate("main", "Set the camera path optimization algorithm. Accepted values are: \n" "gauss: Gaussian kernel low-pass filter on camera motion (default).\n" "avg: Averaging on transformations."), QCoreApplication::translate("main", "campathalgo")); maxShiftOption = new QCommandLineOption( QStringList() << "stab-tr-maxshift", QCoreApplication::translate("main", "Set maximal number of pixels to translate frames. " "Default value is -1, meaning: no limit."), QCoreApplication::translate("main", "maxshift")); maxAngleOption = new QCommandLineOption( QStringList() << "stab-tr-maxangle", QCoreApplication::translate("main", "Set maximal angle in radians (degree*PI/180) to rotate frames. " "Default value is -1, meaning: no limit."), QCoreApplication::translate("main", "maxangle")); cropBlackOption = new QCommandLineOption( QStringList() << "stab-tr-blackcrop", QCoreApplication::translate("main", "Fill empty frame borders by black color. By default is keep image from previous frame.")); invertOption = new QCommandLineOption( QStringList() << "stab-tr-invert", QCoreApplication::translate("main", "Invert transforms.")); relativeOption = new QCommandLineOption( QStringList() << "stab-tr-relative", QCoreApplication::translate("main", "Consider transforms as relative to previous frame. Default is absolute")); zoomOption = new QCommandLineOption( QStringList() << "stab-tr-zoom", QCoreApplication::translate("main", "Set percentage to zoom. A positive value will result in a zoom-in effect, " "a negative value in a zoom-out effect. Default value is 0 (no zoom)."), QCoreApplication::translate("main", "zoom")); optZoomOption = new QCommandLineOption( QStringList() << "stab-tr-optzoom", QCoreApplication::translate("main", "Set optimal zooming to avoid blank-borders. Accepted values are:\n" "0: Disabled.\n" "1: Optimal static zoom value is determined (only very strong movements will lead to visible borders) (default).\n" "2: Optimal adaptive zoom value is determined (no borders will be visible), see zoomspeed.\n" "Note that the value given at zoom is added to the one calculated here."), QCoreApplication::translate("main", "optzoom")); zoomSpeedOption = new QCommandLineOption( QStringList() << "stab-tr-zoomspeed", QCoreApplication::translate("main", "Set percent to zoom maximally each frame (enabled when optzoom is set to 2). " "Range is from 0 to 5, default value is 0.25."), QCoreApplication::translate("main", "zoomspeed")); interpolOption = new QCommandLineOption( QStringList() << "stab-tr-interpol", QCoreApplication::translate("main", "Specify type of interpolation. Available values are:\n" "no: No interpolation.\n" "linear: Linear only horizontal.\n" "bilinear: Linear in both directions (default).\n" "bicubic: Cubic in both directions (slow speed)."), QCoreApplication::translate("main", "interpol")); }
void TestPSD::testPSD() { Kst::VectorPtr vp = Kst::kst_cast<Kst::Vector>(_store.createObject<Kst::Vector>(Kst::ObjectTag::fromString("tempVector"))); Q_ASSERT(vp); vp->resize(10); for (int i = 0; i < 10; i++){ vp->value()[i] = i; } Kst::PSDPtr psd = new Kst::PSD(&_store, Kst::ObjectTag::fromString("psdTest"), vp, 0.0, false, 10, false, false, QString("vUnits"), QString("rUnits"), WindowUndefined, 0.0, PSDUndefined); QCOMPARE(psd->tag().tagString(), QLatin1String("psdTest")); QCOMPARE(psd->vTag(), QLatin1String("tempVector")); QCOMPARE(psd->output(), PSDUndefined); QVERIFY(!psd->apodize()); QVERIFY(!psd->removeMean()); QVERIFY(!psd->average()); QCOMPARE(psd->freq(), 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]); psd->writeLock(); QCOMPARE(psd->update(0), Kst::Object::UPDATE); psd->unlock(); 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->setFreq(0.1); psd->setApodizeFxn(WindowOriginal); psd->setGaussianSigma(0.2); QCOMPARE(psd->tag().tagString(), QLatin1String("psdTest")); QCOMPARE(psd->vTag(), QLatin1String("tempVector")); QCOMPARE(psd->output(), PSDAmplitudeSpectralDensity); QVERIFY(psd->apodize()); QVERIFY(psd->removeMean()); QVERIFY(psd->average()); QCOMPARE(psd->freq(), 0.1); QCOMPARE(psd->apodizeFxn(), WindowOriginal); QCOMPARE(psd->gaussianSigma(), 0.2); // doTest(psd->update(0) == Kst::Object::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(); 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->freq(), 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(); }
Variant TestLocalSocket::randomData(uchar *type, uchar dataAmnt, uchar pkgAmnt, uchar fdAmnt, QFile **targetFile) const { ///@todo Get actual user file number limit and use it here const int maxFiles = 512; // Limit number of files to send if(m_openFiles.count() >= maxFiles) fdAmnt = 0; ushort maxAmnt = dataAmnt + pkgAmnt + fdAmnt; if(maxAmnt == 0) return Variant(); ushort actVal = (qrand()/(double(RAND_MAX)))*maxAmnt; *type = (actVal < dataAmnt ? 0 : (actVal < dataAmnt+pkgAmnt ? 1 : 2)); // *type = qMin(uchar((qrand()/(double(RAND_MAX)))*3), uchar(2)); // 0..2 // *type = qMin(uchar((qrand()/(double(RAND_MAX)))*2), uchar(1)); // 0..1 => no file descriptors yet // *type = 2; // Only file descriptors Variant ret; #define SIZE_MAX 1048576 // 1 M // #define SIZE_MAX 262144 // 256 K switch(*type) { // Random data case 0: case 1: { quint32 size = qMax(quint32((qrand()/double(RAND_MAX))*SIZE_MAX), quint32(1)); // At least one byte QByteArray data; data.reserve(size); for(qint64 j = 0; j < size; j += sizeof(int)) { int r = qrand(); data.append((char*)&r, qMin(int(size - data.size()), (int)sizeof(int))); } ret = data; }break; // File descriptor case 2: { QTemporaryFile * file = new QTemporaryFile(QDir::tempPath() + QDir::separator() + "testlocalsocket"); if(!file->open()) { delete file; qDebug("Could not create temporary file!"); return Variant(); } // Write filename to temp file QFileInfo info(*file); file->write(QString("%1").arg(info.absoluteFilePath()).toUtf8()); file->flush(); file->seek(0); ret = Variant::fromSocketDescriptor(file->handle()); *targetFile = file; }break; } return ret; }
Transformation SVMTrain::analyze(const DataSet* dataset) const { G_INFO("Doing SVMTrain analysis..."); QStringList sdescs = selectDescriptors(dataset->layout(), StringType, _descriptorNames, _exclude, false); if (!sdescs.isEmpty()) { throw GaiaException("SVMTrain: if you want to use string descriptors for training your SVM, " "you first need to enumerate them using the 'enumerate' transform on them. " "String descriptors: ", sdescs.join(", ")); } QStringList descs = selectDescriptors(dataset->layout(), UndefinedType, _descriptorNames, _exclude); // sort descriptors in the order in which they are taken inside the libsvm dataset sort(descs.begin(), descs.end(), DescCompare(dataset->layout())); Region region = dataset->layout().descriptorLocation(descs); QStringList classMapping = svm::createClassMapping(dataset, _className); // first, convert the training data into an SVM problem structure // NB: all checks about fixed-length and type of descriptors are done in this function struct svm_problem prob = svm::dataSetToLibsvmProblem(dataset, _className, region, classMapping); // also get dimension (this trick works because a vector in there is the number // of dimensions + 1 for the sentinel, and we're not in a sparse representation) int dimension = prob.x[1] - prob.x[0] - 1; // default values struct svm_parameter param; //param.svm_type = C_SVC; //param.kernel_type = RBF; //param.degree = 3; //param.gamma = 0; // 1/k param.coef0 = 0; param.nu = 0.5; param.cache_size = 100; //param.C = 1; param.eps = 1e-3; param.p = 0.1; param.shrinking = 1; //param.probability = 0; param.nr_weight = 0; param.weight_label = NULL; param.weight = NULL; // get parameters QString svmType = _params.value("type", "C-SVC").toString().toLower(); param.svm_type = _svmTypeMap.value(svmType); QString kernelType = _params.value("kernel", "RBF").toString().toLower(); param.kernel_type = _kernelTypeMap.value(kernelType); param.degree = _params.value("degree", 3).toInt(); param.C = _params.value("c", 1).toDouble(); param.gamma = _params.value("gamma", 1.0/dimension).toDouble(); param.probability = _params.value("probability", false).toBool() ? 1 : 0; const char* error_msg = svm_check_parameter(&prob, ¶m); if (error_msg) { throw GaiaException(error_msg); } // do it! struct svm_model* model; const bool crossValidation = false; if (crossValidation) { int nr_fold = 10; int total_correct = 0; double total_error = 0; double sumv = 0, sumy = 0, sumvv = 0, sumyy = 0, sumvy = 0; double* target = new double[prob.l]; svm_cross_validation(&prob, ¶m, nr_fold, target); if (param.svm_type == EPSILON_SVR || param.svm_type == NU_SVR) { for (int i=0; i<prob.l; i++) { double y = prob.y[i]; double v = target[i]; total_error += (v-y)*(v-y); sumv += v; sumy += y; sumvv += v*v; sumyy += y*y; sumvy += v*y; } G_INFO("Cross Validation Mean squared error =" << total_error/prob.l); G_INFO("Cross Validation Squared correlation coefficient =" << ((prob.l*sumvy - sumv*sumy) * (prob.l*sumvy - sumv*sumy)) / ((prob.l*sumvv - sumv*sumv) * (prob.l*sumyy - sumy*sumy)) ); } else { for (int i=0; i<prob.l; i++) if (target[i] == prob.y[i]) ++total_correct; G_INFO("Cross Validation Accuracy =" << 100.0*total_correct/prob.l << "%"); } } else { // !crossValidation model = svm_train(&prob, ¶m); } // save model to a temporary file (only method available from libsvm...), // reload it and put it into a gaia2::Parameter QTemporaryFile modelFile; modelFile.open(); QString modelFilename = modelFile.fileName(); modelFile.close(); if (svm_save_model(modelFilename.toAscii().constData(), model) == -1) { throw GaiaException("SVMTrain: error while saving SVM model to temp file"); } modelFile.open(); QByteArray modelData = modelFile.readAll(); modelFile.close(); // if we asked for the model to be output specifically, also do it if (_params.value("modelFilename", "").toString() != "") { QString filename = _params.value("modelFilename").toString(); svm_save_model(filename.toAscii().constData(), model); } // destroy the model allocated by libsvm svm_destroy_model(model); Transformation result(dataset->layout()); result.analyzerName = "svmtrain"; result.analyzerParams = _params; result.applierName = "svmpredict"; result.params.insert("modelData", modelData); result.params.insert("className", _params.value("className")); result.params.insert("descriptorNames", descs); result.params.insert("classMapping", classMapping); result.params.insert("probability", (param.probability == 1 && (param.svm_type == C_SVC || param.svm_type == NU_SVC))); return result; }
void PaymentServerTests::paymentServerTests() { SelectParams(CBaseChainParams::MAIN); OptionsModel optionsModel; PaymentServer* server = new PaymentServer(nullptr, false); X509_STORE* caStore = X509_STORE_new(); X509_STORE_add_cert(caStore, parse_b64der_cert(caCert1_BASE64)); PaymentServer::LoadRootCAs(caStore); server->setOptionsModel(&optionsModel); server->uiReady(); std::vector<unsigned char> data; SendCoinsRecipient r; QString merchant; // Now feed PaymentRequests to server, and observe signals it produces // This payment request validates directly against the // caCert1 certificate authority: data = DecodeBase64(paymentrequest1_cert1_BASE64); r = handleRequest(server, data); r.paymentRequest.getMerchant(caStore, merchant); QCOMPARE(merchant, QString("testmerchant.org")); // Signed, but expired, merchant cert in the request: data = DecodeBase64(paymentrequest2_cert1_BASE64); r = handleRequest(server, data); r.paymentRequest.getMerchant(caStore, merchant); QCOMPARE(merchant, QString("")); // 10-long certificate chain, all intermediates valid: data = DecodeBase64(paymentrequest3_cert1_BASE64); r = handleRequest(server, data); r.paymentRequest.getMerchant(caStore, merchant); QCOMPARE(merchant, QString("testmerchant8.org")); // Long certificate chain, with an expired certificate in the middle: data = DecodeBase64(paymentrequest4_cert1_BASE64); r = handleRequest(server, data); r.paymentRequest.getMerchant(caStore, merchant); QCOMPARE(merchant, QString("")); // 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 BTG): 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; }
DVIExportToPS::DVIExportToPS(dviRenderer& parent, const QString& output_name, const QStringList& options, QPrinter* printer, bool useFontHinting, QPrinter::Orientation orientation) : DVIExport(parent), printer_(printer), orientation_(orientation) { // None of these should happen. Paranoia checks. if (!parent.dviFile) return; const dvifile& dvi = *(parent.dviFile); const QFileInfo input(dvi.filename); if (!input.exists() || !input.isReadable()) return; if (dvi.page_offset.isEmpty()) return; if (dvi.numberOfExternalNONPSFiles != 0) { emit error(i18n("<qt>This DVI file refers to external graphic files which are not in PostScript format, and cannot be handled by the " "<em>dvips</em> program that Okular uses internally to print or to export to PostScript. The functionality that " "you require is therefore unavailable in this version of Okular.</qt>"), -1); return; } if (QStandardPaths::findExecutable(QStringLiteral("dvips")).isEmpty()) { emit error(i18n("<qt><p>Okular could not locate the program <em>dvips</em> on your computer. " "That program is essential for the export function to work.</p>" "<p>Hint to the perplexed system administrator: Okular uses the PATH environment " "variable when looking for programs.</p></qt>"), -1); return; } if (output_name.isEmpty()) return; output_name_ = output_name; // There is a major problem with dvips, at least 5.86 and lower: the // arguments of the option "-pp" refer to TeX-pages, not to // sequentially numbered pages. For instance "-pp 7" may refer to 3 // or more pages: one page "VII" in the table of contents, a page // "7" in the text body, and any number of pages "7" in various // appendices, indices, bibliographies, and so forth. KDVI currently // uses the following disgusting workaround: if the "options" // variable is used, the DVI-file is copied to a temporary file, and // all the page numbers are changed into a sequential ordering // (using UNIX files, and taking manually care of CPU byte // ordering). Finally, dvips is then called with the new file, and // the file is afterwards deleted. Isn't that great? // A similar problem occurs with DVI files that contain page size // information. On these files, dvips pointblank refuses to change // the page orientation or set another page size. Thus, if the // DVI-file does contain page size information, we remove that // information first. // input_name is the name of the DVI which is used by dvips, either // the original file, or a temporary file with a new numbering. QString input_name = dvi.filename; if (!options.isEmpty() || dvi.suggestedPageSize != 0) { // Get a name for a temporary file. // Must open the QTemporaryFile to access the name. QTemporaryFile tmpfile; tmpfile.setAutoRemove(false); tmpfile.open(); tmpfile_name_ = tmpfile.fileName(); tmpfile.close(); input_name = tmpfile_name_; fontPool fp(useFontHinting); dvifile newFile(&dvi, &fp); // Renumber pages newFile.renumber(); const quint16 saved_current_page = parent.current_page; dvifile* saved_dvi = parent.dviFile; parent.dviFile = &newFile; parent.errorMsg = QString(); // Remove any page size information from the file for (parent.current_page = 0; parent.current_page < newFile.total_pages; parent.current_page++) { if (parent.current_page < newFile.total_pages) { parent.command_pointer = newFile.dvi_Data() + parent.dviFile->page_offset[int(parent.current_page)]; parent.end_pointer = newFile.dvi_Data() + parent.dviFile->page_offset[int(parent.current_page+1)]; } else { parent.command_pointer = 0; parent.end_pointer = 0; } memset((char*) &parent.currinf.data, 0, sizeof(parent.currinf.data)); parent.currinf.fonttable = &(parent.dviFile->tn_table); parent.currinf._virtual = 0; parent.prescan(&dviRenderer::prescan_removePageSizeInfo); } parent.current_page = saved_current_page; parent.dviFile = saved_dvi; newFile.saveAs(input_name); } QStringList args; if (!printer) // Export hyperlinks args << QStringLiteral("-z"); if (!options.isEmpty()) args += options; args << input_name << QStringLiteral("-o") << output_name_; start(QStringLiteral("dvips"), args, QFileInfo(dvi.filename).absolutePath(), i18n("<qt>The external program 'dvips', which was used to export the file, reported an error. " "You might wish to look at the <strong>document info dialog</strong> which you will " "find in the File-Menu for a precise error report.</qt>")); }
void ut_tileloading::testMultiOperation() { QTemporaryFile tempFile; tempFile.open(); // The original file may be write protected and edits are disabled for // such files so we need to make a copy QImage originalImage("/usr/share/libquill-tests/images/image_16x4.png"); originalImage.save(tempFile.fileName(), "jpg"); Quill::setDefaultTileSize(QSize(2, 2)); QuillFile *file = new QuillFile(tempFile.fileName(), Strings::jpg); file->setViewPort(QRect(-8, -2, 16, 4)); file->setDisplayLevel(1); QuillImageFilter *filter = QuillImageFilterFactory::createImageFilter(QuillImageFilter::Name_BrightnessContrast); filter->setOption(QuillImageFilter::Brightness, QVariant(20)); QImage referenceImage = filter->apply(originalImage); file->runFilter(filter); Quill::releaseAndWait(); // preview load Quill::releaseAndWait(); // preview filter QCOMPARE(file->allImageLevels().count(), 1); QuillImage previewImage = file->allImageLevels().at(0); QCOMPARE(previewImage.size(), QSize(4, 1)); QCOMPARE(previewImage.fullImageSize(), QSize(16, 4)); Quill::releaseAndWait(); QCOMPARE(file->allImageLevels().count(), 1); Quill::releaseAndWait(); QCOMPARE(file->allImageLevels().count(), 2); QuillImage fragment = file->allImageLevels().at(1); QCOMPARE(fragment.size(), QSize(2, 2)); QCOMPARE(fragment.fullImageSize(), QSize(16, 4)); QCOMPARE(fragment.area(), QRect(0, 0, 2, 2)); Quill::releaseAndWait(); QCOMPARE(file->allImageLevels().count(), 2); Quill::releaseAndWait(); QCOMPARE(file->allImageLevels().count(), 3); fragment = file->allImageLevels().at(2); QCOMPARE(fragment.size(), QSize(2, 2)); QCOMPARE(fragment.fullImageSize(), QSize(16, 4)); QCOMPARE(fragment.area(), QRect(2, 0, 2, 2)); test_utils::analyze((QImage)fragment, referenceImage.copy(2, 0, 2, 2),13); Quill::releaseAndWait(); QCOMPARE(file->allImageLevels().count(), 3); Quill::releaseAndWait(); QCOMPARE(file->allImageLevels().count(), 4); fragment = file->allImageLevels().at(3); QCOMPARE(fragment.size(), QSize(2, 2)); QCOMPARE(fragment.fullImageSize(), QSize(16, 4)); QCOMPARE(fragment.area(), QRect(4, 0, 2, 2)); test_utils::analyze((QImage)fragment, referenceImage.copy(4, 0, 2, 2),13); Quill::releaseAndWait(); QCOMPARE(file->allImageLevels().count(), 4); Quill::releaseAndWait(); QCOMPARE(file->allImageLevels().count(), 5); fragment = file->allImageLevels().at(4); QCOMPARE(fragment.size(), QSize(2, 2)); QCOMPARE(fragment.fullImageSize(), QSize(16, 4)); QCOMPARE(fragment.area(), QRect(6, 0, 2, 2)); test_utils::analyze((QImage)fragment, referenceImage.copy(6, 0, 2, 2),13); delete file; }
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; }
bool KNMusicTagM4a::writeTag(const KNMusicAnalysisItem &analysisItem) { //Get the detail info. const KNMusicDetailInfo &detailInfo=analysisItem.detailInfo; //Prepare and get the music file. QFile musicFile(detailInfo.filePath); //Open the file as read only mode. if(!musicFile.open(QIODevice::ReadOnly)) { //Failed to open the source. return false; } //Generate a temporary file, write the new data to the temporary file. QTemporaryFile updatedTagFile; //Open the temporary file, if we cannot open the temporary file it will be //failed to write the tag. if(!updatedTagFile.open()) { //Close the opened music file. musicFile.close(); return false; } //Generate a data stream for music file. QDataStream musicDataStream(&musicFile); //Read and copy the fytp box. If the first box isn't fytp box, then ignore //the file. M4ABox ftypBox; if(!getBox(musicDataStream, ftypBox) || ftypBox.name!="ftyp") { //Close both file. musicFile.close(); updatedTagFile.close(); //Failed to find a m4a file, return false. return false; } //Write ftyp data to the temporary file. writeBox(ftypBox, updatedTagFile); //We have to keep reading until we find out the moov box. //Output all the other data to updated tag file. M4ABox moovBox; for(;;) { //If we can get a new box. if(getBox(musicDataStream, moovBox)) { //Check out the name. if(moovBox.name=="moov") { break; } else { //Copy the data. writeBox(moovBox, updatedTagFile); } } else { //If we cannot find a box, means there's no "moov" box, failed to //write data. //Close both file. musicFile.close(); updatedTagFile.close(); //Failed to find a m4a file, return false. return false; } } //When we comes to here, we should find the "moov" box, expand the box to //find out the "udta" box. QList<M4ABox> moovExpandList; extractBox(moovBox, moovExpandList); //Generate a empty box for "udta" box. M4ABox udtaBox; //Check the expand list. if(moovExpandList.isEmpty() || !findBox("udta", udtaBox, moovExpandList)) { //If the name of the udta box is still empty, means there's no udta box //in the moov box, then we are faild to parse. //Close both file. musicFile.close(); updatedTagFile.close(); //Failed to find a m4a file, return false. return false; } //Expand the "udta" box, and find "meta" box. QList<M4ABox> udtaExpandList; extractBox(udtaBox, udtaExpandList); //Generate a empty box for "meta" box. M4ABox metaBox; //Check the expand list and find box. if(udtaExpandList.isEmpty() || !findBox("meta", metaBox, udtaExpandList)) { //If the name of the meta box is still empty, means we cannot find meta //box in the meta box, then we are finished to parse. //Close both file. musicFile.close(); updatedTagFile.close(); //Failed to find a m4a file, return false. return false; } //Okay, now we can parse the meta box. //Generate a box for ilst. M4ABox ilstBox; QList<M4ABox> metaExpandList; //Extract the meta box. extractMetaBox(metaBox, metaExpandList); //Find all box of the expand list. if(metaExpandList.isEmpty() || !findBox("ilst", ilstBox, metaExpandList)) { //We cannot find ilst box in the meta box. //Close both file. musicFile.close(); updatedTagFile.close(); //Failed to find a m4a file, return false. return false; } //Prepare the ilst expand list. QList<M4ABox> ilstExpandList; //Expand the ilst box. extractBox(ilstBox, ilstExpandList); //Now we have to write data to ilst expand list. for(int i=0; i<MusicDataCount; ++i) { //Get the atom name of current data. QString atomName=m_indexAtomMap.value(i, QString()); //Check if the atom name is empty, then go to the next. if(atomName.isEmpty()) { continue; } //Remove the exist data inside the ilst expand list. for(int j=ilstExpandList.size()-1; j>-1; --j) { //Check the name of the item. if(ilstExpandList.at(j).name==atomName) { //Remove it. ilstExpandList.removeAt(j); } } //Generate the raw data. QByteArray rawData; //Write the data to raw data. switch(i) { case TrackNumber: //Append three 0x00 first. rawData.append((char)0x00); rawData.append((char)0x00); rawData.append((char)0x00); //Append the track index. rawData.append((char)detailInfo.textLists[TrackNumber].toString() .toInt()); //Append splitter 0x00. rawData.append((char)0x00); //Append the track count. rawData.append((char)detailInfo.textLists[TrackCount].toString() .toInt()); //Append two 0x00 after. rawData.append((char)0x00); rawData.append((char)0x00); break; case DiscNumber: //Append three 0x00 first. rawData.append((char)0x00); rawData.append((char)0x00); rawData.append((char)0x00); //Append the disc index. rawData.append((char)detailInfo.textLists[DiscNumber].toString() .toInt()); //Append splitter 0x00. rawData.append((char)0x00); //Append the disc count. rawData.append((char)detailInfo.textLists[DiscCount].toString() .toInt()); //Append two 0x00 after. rawData.append((char)0x00); rawData.append((char)0x00); break; case Rating: //Append the rating to bytes. rawData.append((char)detailInfo.textLists[Rating].toString() .toInt()); break; default: //Translate the text data to UTF-8, without BOM. rawData=detailInfo.textLists[i].toString().toUtf8(); } //Generate the box. ilstExpandList.append(generateItemBox(i, atomName, rawData)); } //Remove all the album art atom. for(int j=ilstExpandList.size()-1; j>-1; --j) { //Check the name of the item. if(ilstExpandList.at(j).name=="covr") { //Remove it. ilstExpandList.removeAt(j); } } //Check album art. if(!analysisItem.coverImage.isNull()) { //Generate the raw data for the image. //Add the png raw data to image data. QByteArray imageData; QBuffer imageBuffer(&imageData); //Open the image buffer. imageBuffer.open(QIODevice::WriteOnly); //Save the data to image data. analysisItem.coverImage.save(&imageBuffer, "PNG"); //Close the image buffer. imageBuffer.close(); //Check the image data, if the data is not empty, then insert data. if(imageData.isEmpty()) { //Generate the flag data. char covrFlag[5]; covrFlag[0]=0x00; covrFlag[1]=0x00; covrFlag[2]=0x00; covrFlag[3]=14; //Generate item box, insert to list. ilstExpandList.append(generateItemBox(covrFlag, "covr", imageData)); } } //Combine the ilst data together. M4ABox updatedIlstBox=zipBox("ilst", ilstExpandList); //Clear the list and original ilst box. ilstExpandList.clear(); clearBox(ilstBox); //Replace the original ilst box. for(int i=metaExpandList.size()-1; i>-1; --i) { //Check the name. if(metaExpandList.at(i).name=="ilst") { //Replace the item. metaExpandList.replace(i, updatedIlstBox); //Stop searching. break; } } //Combine the meta expand list data. QByteArray metaRawData=combineBoxList(metaExpandList); //Clear up the meta expand list. metaExpandList.clear(); //Append the first four bytes raw data to the meta box raw data. metaRawData.prepend(metaBox.data, 4); //Clear up the no use meta box. clearBox(metaBox); clearBox(updatedIlstBox); //Set the data to new meta box. metaBox.name="meta"; metaBox.independence=true; metaBox.size=metaRawData.size(); metaBox.data=new char[metaBox.size]; memcpy(metaBox.data, metaRawData.data(), metaBox.size); //Replace the original meta box. for(int i=udtaExpandList.size()-1; i>-1; --i) { //Check the name. if(udtaExpandList.at(i).name=="meta") { //Replace the item. udtaExpandList.replace(i, metaBox); //Stop Searching. break; } } //Combine the udta data together. M4ABox updatedUdtaBox=zipBox("udta", udtaExpandList); //Clear the list and original udta box. udtaExpandList.clear(); clearBox(udtaBox); //Replace the original udta box. for(int i=moovExpandList.size()-1; i>-1; --i) { //Check the name. if(moovExpandList.at(i).name=="udta") { //Replace the item moovExpandList.replace(i, updatedUdtaBox); //Stop searching. break; } } //Combine the moov data together. M4ABox updatedMoovBox=zipBox("moov", moovExpandList); //Clear the list and original moov box. moovExpandList.clear(); clearBox(moovBox); //Write the new moov box to the updated tag file. writeBox(updatedMoovBox, updatedTagFile); //Clear up the updated moov box. clearBox(updatedMoovBox); //Copy the left data to the updated tag file. //Generate the music data cache. char *turboCache=new char[DataCacheSize]; //Copy the music data from the original music file, copy the //MusicDataCacheSize bytes once, until there's no bytes to copy. int bytesRead=musicFile.read(turboCache, DataCacheSize); while(bytesRead>0) { //Write the cache to temporary file. updatedTagFile.write(turboCache, bytesRead); //Read new data from the original file to cache. bytesRead=musicFile.read(turboCache, DataCacheSize); } //Close the music file. musicFile.close(); //Reset the temporary file. updatedTagFile.reset(); //Reopen the music file as write only mode, write all the udpated tag file //data to the music file. if(!musicFile.open(QIODevice::WriteOnly)) { //Close the updated tag file. updatedTagFile.close(); //Failed to write data. return false; } //Copy data from temporary file to music file. bytesRead=updatedTagFile.read(turboCache, DataCacheSize); while(bytesRead>0) { //Write the cache to music file. musicFile.write(turboCache, bytesRead); //Read new data from cache to the original file. bytesRead=updatedTagFile.read(turboCache, DataCacheSize); } //Close the music file and temporary file. musicFile.close(); updatedTagFile.close(); //Clear up the turbo memory. delete[] turboCache; //The tag rewrite is finished. return true; }
void ZynAddSubFxInstrument::loadSettings( const QDomElement & _this ) { if( !_this.hasChildNodes() ) { return; } m_portamentoModel.loadSettings( _this, "portamento" ); m_filterFreqModel.loadSettings( _this, "filterfreq" ); m_filterQModel.loadSettings( _this, "filterq" ); m_bandwidthModel.loadSettings( _this, "bandwidth" ); m_fmGainModel.loadSettings( _this, "fmgain" ); m_resCenterFreqModel.loadSettings( _this, "rescenterfreq" ); m_resBandwidthModel.loadSettings( _this, "resbandwidth" ); m_forwardMidiCcModel.loadSettings( _this, "forwardmidicc" ); QDomDocument doc; QDomElement data = _this.firstChildElement( "ZynAddSubFX-data" ); if( data.isNull() ) { data = _this.firstChildElement(); } doc.appendChild( doc.importNode( data, true ) ); QTemporaryFile tf; tf.setAutoRemove( false ); if( tf.open() ) { QByteArray a = doc.toString( 0 ).toUtf8(); tf.write( a ); tf.flush(); const std::string fn = QSTR_TO_STDSTR( QDir::toNativeSeparators( tf.fileName() ) ); m_pluginMutex.lock(); if( m_remotePlugin ) { m_remotePlugin->lock(); m_remotePlugin->sendMessage( RemotePlugin::message( IdLoadSettingsFromFile ).addString( fn ) ); m_remotePlugin->waitForMessage( IdLoadSettingsFromFile ); m_remotePlugin->unlock(); } else { m_plugin->loadXML( fn ); } m_pluginMutex.unlock(); m_modifiedControllers.clear(); for( const QString & c : _this.attribute( "modifiedcontrollers" ).split( ',' ) ) { if( !c.isEmpty() ) { switch( c.toInt() ) { case C_portamento: updatePortamento(); break; case C_filtercutoff: updateFilterFreq(); break; case C_filterq: updateFilterQ(); break; case C_bandwidth: updateBandwidth(); break; case C_fmamp: updateFmGain(); break; case C_resonance_center: updateResCenterFreq(); break; case C_resonance_bandwidth: updateResBandwidth(); break; default: break; } } } emit settingsChanged(); } }
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 (); return result; }
void ut_stack::testSessionSaveLoad() { 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::setEditHistoryPath("/tmp/quill/history"); Quill::setEditHistoryCacheSize(0, 5); QuillFile *file = new QuillFile(testFile.fileName(), Strings::png); file->startSession(); file->runFilter(filter); file->runFilter(filter2); file->endSession(); file->startSession(); file->runFilter(filter3); file->runFilter(filter4); file->endSession(); file->undo(); file->save(); Quill::releaseAndWait(); // load Quill::releaseAndWait(); // filter1 Quill::releaseAndWait(); // filter2 Quill::releaseAndWait(); // save QVERIFY(Unittests::compareImage(QImage(testFile.fileName()), resultImage2)); Quill::cleanup(); Quill::initTestingMode(); Quill::setPreviewSize(0, QSize(8, 2)); Quill::setEditHistoryPath("/tmp/quill/history"); Quill::setEditHistoryCacheSize(0, 5); QuillFile *file2 = new QuillFile(testFile.fileName(), Strings::png); file2->setDisplayLevel(0); Quill::releaseAndWait(); // load QVERIFY(Unittests::compareImage(file2->image(), resultImage2)); file2->redo(); Quill::releaseAndWait(); // load Quill::releaseAndWait(); // filter3 Quill::releaseAndWait(); // filter4 QVERIFY(Unittests::compareImage(file2->image(), resultImage4)); file2->undo(); QVERIFY(Unittests::compareImage(file2->image(), resultImage2)); file2->undo(); Quill::releaseAndWait(); // load QVERIFY(Unittests::compareImage(file2->image(), image)); delete file; delete file2; }
static int assemble(Input input, const QInstaller::Settings &settings) { #ifdef Q_OS_OSX if (QInstaller::isInBundle(input.installerExePath)) { const QString bundle = input.installerExePath; // if the input file was a bundle const QSettings s(QString::fromLatin1("%1/Contents/Info.plist").arg(input.installerExePath), QSettings::NativeFormat); input.installerExePath = QString::fromLatin1("%1/Contents/MacOS/%2").arg(bundle) .arg(s.value(QLatin1String("CFBundleExecutable"), QFileInfo(input.installerExePath).completeBaseName()).toString()); } const bool createDMG = input.outputPath.endsWith(QLatin1String(".dmg")); if (createDMG) input.outputPath.replace(input.outputPath.length() - 4, 4, QLatin1String(".app")); const bool isBundle = input.outputPath.endsWith(QLatin1String(".app")); const QString bundle = isBundle ? input.outputPath : QString(); const BundleBackup bundleBackup(bundle); if (isBundle) { // output should be a bundle const QFileInfo fi(input.outputPath); const QString contentsResourcesPath = fi.filePath() + QLatin1String("/Contents/Resources/"); QInstaller::mkpath(fi.filePath() + QLatin1String("/Contents/MacOS")); QInstaller::mkpath(contentsResourcesPath); { QFile pkgInfo(fi.filePath() + QLatin1String("/Contents/PkgInfo")); pkgInfo.open(QIODevice::WriteOnly); QTextStream pkgInfoStream(&pkgInfo); pkgInfoStream << QLatin1String("APPL????") << endl; } QString iconFile; if (QFile::exists(settings.installerApplicationIcon())) { iconFile = settings.installerApplicationIcon(); } else { iconFile = QString::fromLatin1(":/resources/default_icon_mac.icns"); } const QString iconTargetFile = fi.completeBaseName() + QLatin1String(".icns"); QFile::copy(iconFile, contentsResourcesPath + iconTargetFile); if (QDir(qApp->applicationDirPath() + QLatin1String("/qt_menu.nib")).exists()) { copyDirectoryContents(qApp->applicationDirPath() + QLatin1String("/qt_menu.nib"), contentsResourcesPath + QLatin1String("/qt_menu.nib")); } QFile infoPList(fi.filePath() + QLatin1String("/Contents/Info.plist")); infoPList.open(QIODevice::WriteOnly); QTextStream plistStream(&infoPList); plistStream << QLatin1String("<?xml version=\"1.0\" encoding=\"UTF-8\"?>") << endl; plistStream << QLatin1String("<!DOCTYPE plist SYSTEM \"file://localhost/System/Library/DTDs" "/PropertyList.dtd\">") << endl; plistStream << QLatin1String("<plist version=\"0.9\">") << endl; plistStream << QLatin1String("<dict>") << endl; plistStream << QLatin1String(" <key>CFBundleIconFile</key>") << endl; plistStream << QLatin1String(" <string>") << iconTargetFile << QLatin1String("</string>") << endl; plistStream << QLatin1String(" <key>CFBundlePackageType</key>") << endl; plistStream << QLatin1String(" <string>APPL</string>") << endl; plistStream << QLatin1String(" <key>CFBundleGetInfoString</key>") << endl; #define QUOTE_(x) #x #define QUOTE(x) QUOTE_(x) plistStream << QLatin1String(" <string>") << QLatin1String(QUOTE(IFW_VERSION_STR)) << ("</string>") << endl; #undef QUOTE #undef QUOTE_ plistStream << QLatin1String(" <key>CFBundleSignature</key>") << endl; plistStream << QLatin1String(" <string> ???? </string>") << endl; plistStream << QLatin1String(" <key>CFBundleExecutable</key>") << endl; plistStream << QLatin1String(" <string>") << fi.completeBaseName() << QLatin1String("</string>") << endl; plistStream << QLatin1String(" <key>CFBundleIdentifier</key>") << endl; plistStream << QLatin1String(" <string>com.yourcompany.installerbase</string>") << endl; plistStream << QLatin1String(" <key>NOTE</key>") << endl; plistStream << QLatin1String(" <string>This file was generated by Qt Installer Framework.</string>") << endl; plistStream << QLatin1String(" <key>NSPrincipalClass</key>") << endl; plistStream << QLatin1String(" <string>NSApplication</string>") << endl; plistStream << QLatin1String("</dict>") << endl; plistStream << QLatin1String("</plist>") << endl; input.outputPath = QString::fromLatin1("%1/Contents/MacOS/%2").arg(input.outputPath) .arg(fi.completeBaseName()); } #elif defined(Q_OS_LINUX) Q_UNUSED(settings) #endif QTemporaryFile file(input.outputPath); if (!file.open()) { throw Error(QString::fromLatin1("Cannot copy %1 to %2: %3").arg(input.installerExePath, input.outputPath, file.errorString())); } const QString tempFile = file.fileName(); file.close(); file.remove(); QFile instExe(input.installerExePath); if (!instExe.copy(tempFile)) { throw Error(QString::fromLatin1("Cannot copy %1 to %2: %3").arg(instExe.fileName(), tempFile, instExe.errorString())); } QtPatch::patchBinaryFile(tempFile, QByteArray("MY_InstallerCreateDateTime_MY"), QDateTime::currentDateTime().toString(QLatin1String("yyyy-MM-dd - HH:mm:ss")).toLatin1()); input.installerExePath = tempFile; #if defined(Q_OS_WIN) // setting the windows icon must happen before we append our binary data - otherwise they get lost :-/ if (QFile::exists(settings.installerApplicationIcon())) { // no error handling as this is not fatal setApplicationIcon(tempFile, settings.installerApplicationIcon()); } #elif defined(Q_OS_OSX) if (isBundle) { // no error handling as this is not fatal const QString copyscript = QDir::temp().absoluteFilePath(QLatin1String("copylibsintobundle.sh")); QFile::copy(QLatin1String(":/resources/copylibsintobundle.sh"), copyscript); QFile::rename(tempFile, input.outputPath); chmod755(copyscript); QProcess p; p.start(copyscript, QStringList() << bundle); p.waitForFinished(); QFile::rename(input.outputPath, tempFile); QFile::remove(copyscript); } #endif QTemporaryFile out; QString targetName = input.outputPath; #ifdef Q_OS_OSX QDir resourcePath(QFileInfo(input.outputPath).dir()); resourcePath.cdUp(); resourcePath.cd(QLatin1String("Resources")); targetName = resourcePath.filePath(QLatin1String("installer.dat")); #endif { QFile target(targetName); if (target.exists() && !target.remove()) { qCritical("Cannot remove target %s: %s", qPrintable(target.fileName()), qPrintable(target.errorString())); QFile::remove(tempFile); return EXIT_FAILURE; } } try { QInstaller::openForWrite(&out); QFile exe(input.installerExePath); #ifdef Q_OS_OSX if (!exe.copy(input.outputPath)) { throw Error(QString::fromLatin1("Cannot copy %1 to %2: %3").arg(exe.fileName(), input.outputPath, exe.errorString())); } #else QInstaller::openForRead(&exe); QInstaller::appendData(&out, &exe, exe.size()); #endif foreach (const QInstallerTools::PackageInfo &info, input.packages) { QInstaller::ResourceCollection collection; collection.setName(info.name.toUtf8()); qDebug() << "Creating resource archive for" << info.name; foreach (const QString &file, info.copiedFiles) { const QSharedPointer<Resource> resource(new Resource(file)); qDebug() << QString::fromLatin1("Appending %1 (%2)").arg(file, humanReadableSize(resource->size())); collection.appendResource(resource); } input.manager.insertCollection(collection); } const QList<QInstaller::OperationBlob> operations; BinaryContent::writeBinaryContent(&out, operations, input.manager, BinaryContent::MagicInstallerMarker, BinaryContent::MagicCookie); } catch (const Error &e) { qCritical("Error occurred while assembling the installer: %s", qPrintable(e.message())); QFile::remove(tempFile); return EXIT_FAILURE; } if (!out.rename(targetName)) { qCritical("Cannot write installer to %s: %s", targetName.toUtf8().constData(), out.errorString().toUtf8().constData()); QFile::remove(tempFile); return EXIT_FAILURE; } out.setAutoRemove(false); #ifndef Q_OS_WIN chmod755(out.fileName()); #endif QFile::remove(tempFile); #ifdef Q_OS_OSX bundleBackup.release(); if (createDMG) { qDebug() << "creating a DMG disk image..."; // no error handling as this is not fatal const QString mkdmgscript = QDir::temp().absoluteFilePath(QLatin1String("mkdmg.sh")); QFile::copy(QLatin1String(":/resources/mkdmg.sh"), mkdmgscript); chmod755(mkdmgscript); QProcess p; p.start(mkdmgscript, QStringList() << QFileInfo(input.outputPath).fileName() << bundle); p.waitForFinished(); QFile::remove(mkdmgscript); qDebug() << "done." << mkdmgscript; } #endif return EXIT_SUCCESS; }
bool KNMusicTagApev2::writeTag(const KNMusicAnalysisItem &analysisItem) { //Write the data according to the detail info. const KNMusicDetailInfo &detailInfo=analysisItem.detailInfo; //Check the file is still exist or not. QFile musicFile(detailInfo.filePath); //If the file is not exist then return false. if(!musicFile.exists()) { return false; } //Find the original tag data. //ID3v1 header flag. bool hasId3v1=false; //Generate a header structure. APEHeader header; //Generate the raw tag data list. QList<APETagItem> itemList; //Initial the tag start position. qint64 tagDataStart=-1, tagDataLength=-1; //Open the file first. if(musicFile.open(QIODevice::ReadOnly)) { //Generate a data stream. QDataStream musicDataStream(&musicFile); if(musicFile.size() > 128) { //ID3v1 header cache. char id3v1Header[3]; //Check whether there's ID3v1 tag in the music file. musicDataStream.skipRawData(musicFile.size()-128); //Read ID3v1 header. musicDataStream.readRawData(id3v1Header, 3); //Check the header, and we can know that whether there's ID3v1 //header. hasId3v1=(id3v1Header[0]=='T' && id3v1Header[1]=='A' && id3v1Header[2]=='G'); } //Check the beginning of the file. if(checkHeader(0, musicDataStream, header)) { //Set the tag data start. tagDataStart=0; //Set the tag length to header length. tagDataLength=header.size; //Check whether is a footer in the tag. if(header.size > APEv2HeaderSize) { //Check the footer. APEHeader footer; //Tried to parse the footer. if(checkHeader(header.size, musicDataStream, footer)) { //Update the tag length. tagDataLength+=APEv2HeaderSize; } } //Reset the device to start. musicDataStream.device()->reset(); //Skip the file data. musicDataStream.skipRawData(APEv2HeaderSize); } //Check the end of the file. else if(checkHeader(musicFile.size()-APEv2HeaderSize, musicDataStream, header)) { //Save the tag start data. int tagContentStart=musicFile.size()-header.size; //Check the footer. APEHeader footer; //Check whether there's a header in the tag. if(checkHeader(tagContentStart-APEv2HeaderSize, musicDataStream, footer)) { //Save the tag data start position as the header start position. //This is APEv2 tag. tagDataStart=tagContentStart-APEv2HeaderSize; //The tag length will be a header size + tag size. tagDataLength=APEv2HeaderSize + header.size; } else { //This is APEv1 tag. tagDataStart=tagContentStart; //The tag length will be tag size. tagDataLength=header.size; } //Reset the device to start. musicDataStream.device()->reset(); //Skip the file data. musicDataStream.skipRawData(tagContentStart); } //Check the position before ID3v1. Some file may have both ID3v1 and //APEv1/APEv2. else if(musicFile.size()>=(ID3v1nAPEv2 + APEv2HeaderSize) && //File size first. checkHeader(musicFile.size()-ID3v1nAPEv2, musicDataStream, header)) { //Save the tag start position. int tagContentStart=musicFile.size()-ID3v1Size-header.size; //Check the footer. APEHeader footer; //Check whether there's a header in the tag. if(checkHeader(tagContentStart-APEv2HeaderSize, musicDataStream, footer)) { //Save the tag data start position as the header start position. //This is APEv2 tag. tagDataStart=tagContentStart-APEv2HeaderSize; //The tag length will be a header size + tag size. tagDataLength=APEv2HeaderSize + header.size; } else { //This is APEv1 tag. tagDataStart=tagContentStart; //The tag length will be tag size. tagDataLength=header.size; } //Reset the device to start. musicDataStream.device()->reset(); //Skip the file data. musicDataStream.skipRawData(tagContentStart); } //Parse the data if we find the header. if(tagDataStart!=-1) { //Read the tag from the file. char *rawTagData=new char[header.size]; musicDataStream.readRawData(rawTagData, header.size); //Parse the raw tag data list. parseRawData(rawTagData, header, itemList); //Recover the memory. delete[] rawTagData; } //Close the music file. musicFile.close(); } //Add all the text labels to detail frames if it's not empty. for(int i=0; i<MusicDataCount; i++) { //Check if the text is empty. if(detailInfo.textLists[i].toString().isEmpty()) { continue; } //Get the frame key from hash group. QString key=m_indexKey.value(i, QString()); //If the key is empty, means you cannot write this data to APEv2. if(key.isEmpty()) { continue; } //Generate a data frame. APETagItem item; //Save the key. item.key=key; //According to the frame, generate the item. switch(i) { case DiscNumber: //If disc count isn't empty, then add disc count to disc number //data. item.value=detailInfo.textLists[DiscCount].toString().isEmpty()? detailInfo.textLists[DiscNumber].toString().toUtf8(): (detailInfo.textLists[DiscNumber].toString()+"/"+ detailInfo.textLists[DiscCount].toString()).toUtf8(); default: //Add the whole data to the item. item.value=detailInfo.textLists[i].toString().toUtf8(); } //Remove the all the original item. //We have to check the key from the back to the first, and we won't get //mess to the index. for(int i=itemList.size()-1; i>-1; i--) { //If the key is the same as current key, if(itemList.at(i).key==key) { //Remove it. itemList.removeAt(i); } } //Add current key to item list. itemList.append(item); } //Now translate the frame structure data to the raw data. QByteArray contentData; //Prepare the cache size. char numberCache[4]; //Simply transferred the APETagItem to content data. for(auto i=itemList.constBegin(); i!=itemList.constEnd(); ++i) { //Get the item size. quint32 size=(*i).value.size(); //First transfer item size to raw data into cache. numberToData(size, numberCache); //Add item size to content data. contentData.append(numberCache, 4); //Transfer the flag to raw data into cache. numberToData((*i).flag, numberCache); //Add flag data to content data. contentData.append(numberCache, 4); //Add item key to content data. contentData.append((*i).key.toUtf8()); //Add 0x00 for item key terminator. contentData.append('\0'); //Add item value. contentData.append((*i).value); } //Update the header data. header.size=contentData.size()+32; header.itemCount=itemList.size(); //We will write the APEv2 data to the end part of the file. Just before the //ID3v1. //Check the header data. //Open the music file again. if(!musicFile.open(QIODevice::ReadOnly)) { return false; } //Generate a temporary file, write the new data to the temporary file. QTemporaryFile updatedTagFile; //Open the temporary file, if we cannot open the temporary file it will be //failed to write the tag. if(!updatedTagFile.open()) { //Close the opened music file. musicFile.close(); return false; } //Initial the file size. qint64 dataSurplusSize=musicFile.size(); /* * Algorithm: * We treat the file as these two kinds of format: * APEv2 | xxxx (Content) (| ID3v1) * or * xxxx (Content) | APEv2 (| ID3v1) * So we have to process the ID3v1 at first. Then the file should be like * the following: * APEv2 | xxxx (Content) * or * xxxx (Content) | APEv2 * And now, we only have to check if the APEv2 is at the beginning or the * end of the content. */ //If we have ID3v1, then remove the tag from the copying bytes. if(hasId3v1) { //Reduce the ID3v1 tag size. dataSurplusSize-=128; } //Check whether we have original APEv2 header. if(tagDataStart!=-1) { //Reduce the tag size from the file size. dataSurplusSize-=tagDataLength; //Check whether the header is at the start of the music file. if(tagDataStart==0) { //It's at the beginning of the file. //Skip the Original APEv2 tag at the beginning of the file. musicFile.seek(tagDataLength); } } //Generate the music data cache. char *turboCache=new char[DataCacheSize]; int bytesRead; //Now copy all the content from the original file to temporary file. while(dataSurplusSize>0) { //Read the original data. bytesRead=musicFile.read(turboCache, (DataCacheSize < dataSurplusSize ? DataCacheSize : dataSurplusSize)); //Write the cache to temporary file. updatedTagFile.write(turboCache, bytesRead); //Reduce the surplus size. dataSurplusSize-=bytesRead; } //According to the hydrogenaud.io, we have to put the APEv2 at the end of //the file. //Write new APEv2 tag to the file. /* * From http://wiki.hydrogenaud.io/index.php?title=Ape_Tags_Flags: * Bit 29: * 0: This is the footer, not the header * 1: This is the header, not the footer */ //First set the item flag to header in header data bytearray. updatedTagFile.write(generateHeaderData(header, true)); //Then, write the content data. updatedTagFile.write(contentData); //Last, write the footer data. updatedTagFile.write(generateHeaderData(header, false)); //If there's ID3v1 tag, then copy the ID3v1 data from the original file. if(hasId3v1) { //Seek to the ID3v1 tag start. musicFile.seek(musicFile.size()-128); //Read 128 bytes ID3v1 tag. musicFile.read(turboCache, 128); //Write the cache to temporary file. updatedTagFile.write(turboCache, 128); } //Close the music file. musicFile.close(); //Reset the temporary file. updatedTagFile.reset(); //Reopen the music file as write only mode, write all the udpated tag file //data to the music file. if(!musicFile.open(QIODevice::WriteOnly)) { return false; } //Copy data from temporary file to music file. bytesRead=updatedTagFile.read(turboCache, DataCacheSize); while(bytesRead>0) { //Write the cache to music file. musicFile.write(turboCache, bytesRead); //Read new data from the original file to cache. bytesRead=updatedTagFile.read(turboCache, DataCacheSize); } //Close the music file and temporary file. musicFile.close(); updatedTagFile.close(); //Clear up the turbo cache. delete[] turboCache; //The tag rewrite is finished. return true; }
tristate SqliteVacuum::run() { const QString dump_app = QString::fromLatin1(KDB_SQLITE_DUMP_TOOL); //sqliteDebug() << dump_app; if (dump_app.isEmpty()) { m_result = KDbResult(ERR_OBJECT_NOT_FOUND, tr("Could not find tool \"%1\".") .arg(dump_app)); sqliteWarning() << m_result; return false; } const QString sqlite_app(KDb::sqlite3ProgramPath()); //sqliteDebug() << sqlite_app; if (sqlite_app.isEmpty()) { m_result = KDbResult(ERR_OBJECT_NOT_FOUND, tr("Could not find application \"%1\".") .arg(sqlite_app)); sqliteWarning() << m_result; return false; } QFileInfo fi(m_filePath); if (!fi.isReadable()) { m_result = KDbResult(ERR_OBJECT_NOT_FOUND, tr("Could not read file \"%1\".") .arg(m_filePath)); sqliteWarning() << m_result; return false; } //sqliteDebug() << fi.absoluteFilePath() << fi.absoluteDir().path(); delete m_dumpProcess; m_dumpProcess = new QProcess(this); m_dumpProcess->setWorkingDirectory(fi.absoluteDir().path()); m_dumpProcess->setReadChannel(QProcess::StandardError); connect(m_dumpProcess, SIGNAL(readyReadStandardError()), this, SLOT(readFromStdErr())); connect(m_dumpProcess, SIGNAL(finished(int,QProcess::ExitStatus)), this, SLOT(dumpProcessFinished(int,QProcess::ExitStatus))); delete m_sqliteProcess; m_sqliteProcess = new QProcess(this); m_sqliteProcess->setWorkingDirectory(fi.absoluteDir().path()); connect(m_sqliteProcess, SIGNAL(finished(int,QProcess::ExitStatus)), this, SLOT(sqliteProcessFinished(int,QProcess::ExitStatus))); m_dumpProcess->setStandardOutputProcess(m_sqliteProcess); m_dumpProcess->start(dump_app, QStringList() << fi.absoluteFilePath()); if (!m_dumpProcess->waitForStarted()) { delete m_dumpProcess; m_dumpProcess = 0; m_result.setCode(ERR_OTHER); return false; } QTemporaryFile *tempFile = new QTemporaryFile(fi.absoluteFilePath()); tempFile->open(); m_tmpFilePath = tempFile->fileName(); delete tempFile; //sqliteDebug() << m_tmpFilePath; m_sqliteProcess->start(sqlite_app, QStringList() << m_tmpFilePath); if (!m_sqliteProcess->waitForStarted()) { delete m_dumpProcess; m_dumpProcess = 0; delete m_sqliteProcess; m_sqliteProcess = 0; m_result.setCode(ERR_OTHER); return false; } delete m_dlg; m_dlg = new QProgressDialog(0); // krazy:exclude=qclasses m_dlg->setWindowTitle(tr("Compacting database")); m_dlg->setLabelText( QLatin1String("<qt>") + tr("Compacting database \"%1\"...") .arg(QLatin1String("<nobr>") + QDir::fromNativeSeparators(fi.fileName()) + QLatin1String("</nobr>")) ); m_dlg->adjustSize(); m_dlg->resize(300, m_dlg->height()); m_dlg->setMinimumDuration(1000); m_dlg->setAutoClose(true); m_dlg->setRange(0, 100); m_dlg->exec(); if (m_dlg->wasCanceled()) { cancelClicked(); } delete m_dlg; m_dlg = 0; while (m_dumpProcess->state() == QProcess::Running && m_sqliteProcess->state() == QProcess::Running) { readFromStdErr(); qApp->processEvents(QEventLoop::AllEvents, 50000); } readFromStdErr(); return true; }