unsigned int FileUtils::getFileSize(const QString &filePath) { QFileInfo fileInfo(filePath); return fileInfo.size(); }
bool MainWindow2::saveObject( QString strSavedFilename ) { QString filePath = strSavedFilename; bool savingTheOLDWAY = filePath.endsWith( PFF_OLD_EXTENSION ); QFileInfo fileInfo( filePath ); if ( fileInfo.isDir() ) return false; QString tmpFilePath; if ( !savingTheOLDWAY ) {// create temporary directory for compressing files tmpFilePath = QDir::tempPath() + "/" + fileInfo.completeBaseName() + PFF_TMP_COMPRESS_EXT; QFileInfo tmpDataInfo( tmpFilePath ); if ( !tmpDataInfo.exists() ) { QDir dir( QDir::tempPath() ); // --the directory where filePath is or will be saved dir.mkpath( tmpFilePath ); // --creates a directory with the same name +".data" } } else { tmpFilePath = fileInfo.absolutePath(); } QString dataLayersDir; if ( savingTheOLDWAY ) { dataLayersDir = filePath + "." + PFF_LAYERS_DIR; } else { dataLayersDir = tmpFilePath + "/" + PFF_LAYERS_DIR; } QFileInfo dataInfo( dataLayersDir ); if ( !dataInfo.exists() ) { QDir dir( tmpFilePath ); // the directory where filePath is or will be saved dir.mkpath( dataLayersDir ); // creates a directory with the same name +".data" } //savedName = filePath; this->setWindowTitle( filePath ); QProgressDialog progress( tr("Saving document..."), tr("Abort"), 0, 100, this ); progress.setWindowModality( Qt::WindowModal ); progress.show(); int progressValue = 0; // save data int nLayers = m_object->getLayerCount(); qDebug( "Layer Count=%d", nLayers ); for ( int i = 0; i < nLayers; i++ ) { Layer* layer = m_object->getLayer( i ); qDebug() << "Saving Layer " << i << "(" << layer->name << ")"; progressValue = (i * 100) / nLayers; progress.setValue( progressValue ); if ( layer->type() == Layer::BITMAP ) ((LayerBitmap*)layer)->saveImages( dataLayersDir, i ); if ( layer->type() == Layer::VECTOR ) ((LayerVector*)layer)->saveImages( dataLayersDir, i ); if ( layer->type() == Layer::SOUND ) ((LayerSound*)layer)->saveImages( dataLayersDir, i ); } // save palette m_object->savePalette( dataLayersDir ); // -------- save main XML file ----------- QString mainXMLfile; if ( !savingTheOLDWAY ) { mainXMLfile = tmpFilePath + "/" + PFF_XML_FILE_NAME; } else { mainXMLfile = filePath; } QFile* file = new QFile( mainXMLfile ); if ( !file->open( QFile::WriteOnly | QFile::Text ) ) { //QMessageBox::warning(this, "Warning", "Cannot write file"); return false; } QTextStream out( file ); QDomDocument doc( "PencilDocument" ); QDomElement root = doc.createElement( "document" ); doc.appendChild( root ); // save editor information QDomElement editorElement = createDomElement( doc ); root.appendChild( editorElement ); qDebug( "Save Editor Node." ); // save object QDomElement objectElement = m_object->createDomElement( doc ); root.appendChild( objectElement ); qDebug( "Save Object Node." ); int IndentSize = 2; doc.save( out, IndentSize ); // ----------------------------------- if ( !savingTheOLDWAY ) { qDebug() << "Now compressing data to PFF - PCLX ..."; JlCompress::compressDir( filePath, tmpFilePath ); removePFFTmpDirectory( tmpFilePath ); // --removing temporary files qDebug() << "Compressed. File saved."; } progress.setValue( 100 ); m_object->modified = false; m_pTimeLine->updateContent(); m_object->setFilePath( strSavedFilename ); m_recentFileMenu->addRecentFile( strSavedFilename ); m_recentFileMenu->saveToDisk(); return true; }
void tst_QAudioDecoderBackend::deviceTest() { QAudioDecoder d; QAudioBuffer buffer; quint64 duration = 0; int sampleCount = 0; QSignalSpy readySpy(&d, SIGNAL(bufferReady())); QSignalSpy bufferChangedSpy(&d, SIGNAL(bufferAvailableChanged(bool))); QSignalSpy errorSpy(&d, SIGNAL(error(QAudioDecoder::Error))); QSignalSpy stateSpy(&d, SIGNAL(stateChanged(QAudioDecoder::State))); QSignalSpy durationSpy(&d, SIGNAL(durationChanged(qint64))); QSignalSpy finishedSpy(&d, SIGNAL(finished())); QSignalSpy positionSpy(&d, SIGNAL(positionChanged(qint64))); QVERIFY(d.state() == QAudioDecoder::StoppedState); QVERIFY(d.bufferAvailable() == false); QCOMPARE(d.sourceFilename(), QString("")); QVERIFY(d.audioFormat() == QAudioFormat()); QFileInfo fileInfo(QFINDTESTDATA(TEST_FILE_NAME)); QFile file(fileInfo.absoluteFilePath()); QVERIFY(file.open(QIODevice::ReadOnly)); d.setSourceDevice(&file); QVERIFY(d.sourceDevice() == &file); QVERIFY(d.sourceFilename().isEmpty()); // We haven't set the format yet QVERIFY(d.audioFormat() == QAudioFormat()); d.start(); QTRY_VERIFY(d.state() == QAudioDecoder::DecodingState); QTRY_VERIFY(!stateSpy.isEmpty()); QTRY_VERIFY(!readySpy.isEmpty()); QTRY_VERIFY(!bufferChangedSpy.isEmpty()); QVERIFY(d.bufferAvailable()); QTRY_VERIFY(!durationSpy.isEmpty()); QVERIFY(qAbs(d.duration() - 1000) < 20); buffer = d.read(); QVERIFY(buffer.isValid()); // Test file is 44.1K 16bit mono QCOMPARE(buffer.format().channelCount(), 1); QCOMPARE(buffer.format().sampleRate(), 44100); QCOMPARE(buffer.format().sampleSize(), 16); QCOMPARE(buffer.format().sampleType(), QAudioFormat::SignedInt); QCOMPARE(buffer.format().codec(), QString("audio/pcm")); QVERIFY(errorSpy.isEmpty()); duration += buffer.duration(); sampleCount += buffer.sampleCount(); // Now drain the decoder if (sampleCount < 44094) { QTRY_COMPARE(d.bufferAvailable(), true); } while (d.bufferAvailable()) { buffer = d.read(); QVERIFY(buffer.isValid()); QTRY_VERIFY(!positionSpy.isEmpty()); QVERIFY(positionSpy.takeLast().at(0).toLongLong() == qint64(duration / 1000)); QVERIFY(d.position() - (duration / 1000) < 20); duration += buffer.duration(); sampleCount += buffer.sampleCount(); if (sampleCount < 44094) { QTRY_COMPARE(d.bufferAvailable(), true); } } // Make sure the duration is roughly correct (+/- 20ms) QCOMPARE(sampleCount, 44094); QVERIFY(qAbs(qint64(duration) - 1000000) < 20000); QVERIFY(qAbs((d.position() + (buffer.duration() / 1000)) - 1000) < 20); QTRY_COMPARE(finishedSpy.count(), 1); QVERIFY(!d.bufferAvailable()); QTRY_COMPARE(d.state(), QAudioDecoder::StoppedState); d.stop(); QTRY_COMPARE(d.state(), QAudioDecoder::StoppedState); QVERIFY(!d.bufferAvailable()); QTRY_COMPARE(durationSpy.count(), 2); QCOMPARE(d.duration(), qint64(-1)); readySpy.clear(); bufferChangedSpy.clear(); stateSpy.clear(); durationSpy.clear(); finishedSpy.clear(); positionSpy.clear(); // Now try changing formats QAudioFormat format; format.setChannelCount(2); format.setSampleSize(8); format.setSampleRate(8000); format.setCodec("audio/pcm"); format.setSampleType(QAudioFormat::SignedInt); d.setAudioFormat(format); // Make sure it stuck QVERIFY(d.audioFormat() == format); d.start(); QTRY_VERIFY(d.state() == QAudioDecoder::DecodingState); QTRY_VERIFY(!stateSpy.isEmpty()); QTRY_VERIFY(!readySpy.isEmpty()); QTRY_VERIFY(!bufferChangedSpy.isEmpty()); QVERIFY(d.bufferAvailable()); QTRY_VERIFY(!durationSpy.isEmpty()); QVERIFY(qAbs(d.duration() - 1000) < 20); buffer = d.read(); QVERIFY(buffer.isValid()); // See if we got the right format QVERIFY(buffer.format() == format); // The decoder should still have the same format QVERIFY(d.audioFormat() == format); QVERIFY(errorSpy.isEmpty()); d.stop(); QTRY_COMPARE(d.state(), QAudioDecoder::StoppedState); QVERIFY(!d.bufferAvailable()); QTRY_COMPARE(durationSpy.count(), 2); QCOMPARE(d.duration(), qint64(-1)); }
void Rshare::loadStyleSheet(const QString &sheetName) { QString locale = QLocale().name(); QString styleSheet; QStringList names; names.push_back(""); // RetroShare /* Get stylesheet from plugins */ if (rsPlugins) { int count = rsPlugins->nbPlugins(); for (int i = 0; i < count; ++i) { RsPlugin* plugin = rsPlugins->plugin(i); if (plugin) { QString pluginStyleSheetName = QString::fromUtf8(plugin->qt_stylesheet().c_str()); if (!pluginStyleSheetName.isEmpty()) { names.push_back(QString("%1/%1_").arg(pluginStyleSheetName)); } } } } foreach (QString name, names) { /* load the default stylesheet */ QFile file(QString(":/qss/stylesheet/%1qss.default").arg(name)); if (file.open(QFile::ReadOnly)) { styleSheet += QLatin1String(file.readAll()) + "\n"; file.close(); } /* load locale depended default stylesheet */ file.setFileName(QString(":/qss/stylesheet/%1qss.%2").arg(name, locale)); if (file.open(QFile::ReadOnly)) { styleSheet += QLatin1String(file.readAll()) + "\n"; file.close(); } if (!sheetName.isEmpty()) { /* load stylesheet */ if (sheetName.left(1) == ":") { /* internal stylesheet */ file.setFileName(QString(":/qss/stylesheet/%1%2.qss").arg(name, sheetName.mid(1))); } else { /* external stylesheet */ file.setFileName(QString("%1/qss/%2%3.qss").arg(QString::fromUtf8(RsAccounts::ConfigDirectory().c_str()), name, sheetName)); if (!file.exists()) { file.setFileName(QString("%1/qss/%2%3.qss").arg(QString::fromUtf8(RsAccounts::DataDirectory().c_str()), name, sheetName)); } } if (file.open(QFile::ReadOnly)) { styleSheet += QLatin1String(file.readAll()) + "\n"; file.close(); /* load language depended stylesheet */ QFileInfo fileInfo(file.fileName()); file.setFileName(fileInfo.path() + "/" + fileInfo.baseName() + "_" + locale + ".lqss"); if (file.open(QFile::ReadOnly)) { styleSheet += QLatin1String(file.readAll()) + "\n"; file.close(); } } } }
void ClipObject::loadImage(QString imgFile, int imgFrame) { if (m_imageName == imgFile && m_imageFrame == imgFrame) return; m_imageName = imgFile; m_imageFrame = imgFrame; if (m_imageName.isEmpty()) { m_imageFrame = 0; m_imagePresent = false; return; } //---------------- // file is assumed to be relative to .pvl.nc file // get the absolute path VolumeInformation pvlInfo = VolumeInformation::volumeInformation(); QFileInfo fileInfo(pvlInfo.pvlFile); QString absoluteImageFile = QFileInfo(fileInfo.absolutePath(), m_imageName).absoluteFilePath(); //---------------- QFileInfo f(absoluteImageFile); if (f.exists() == false) { m_textureHeight = m_textureWidth = 10; m_imagePresent = true; clearCaption(); return; } QMovie movie(absoluteImageFile); movie.setCacheMode(QMovie::CacheAll); movie.start(); movie.setPaused(true); movie.jumpToFrame(0); if (movie.jumpToFrame(m_imageFrame) == false) movie.jumpToFrame(0); QImage mapImage(movie.currentImage()); m_textureHeight = mapImage.height(); m_textureWidth = mapImage.width(); int nbytes = mapImage.byteCount(); int rgb = nbytes/(m_textureWidth*m_textureHeight); unsigned char *image = new unsigned char[rgb*m_textureWidth*m_textureHeight]; memcpy(image, mapImage.bits(), rgb*m_textureWidth*m_textureHeight); GLuint fmt; if (rgb == 1) fmt = GL_LUMINANCE; else if (rgb == 2) fmt = GL_LUMINANCE_ALPHA; else if (rgb == 3) fmt = GL_RGB; else if (rgb == 4) fmt = GL_BGRA; glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_RECTANGLE_ARB, m_imageTex); glTexParameterf(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, rgb, m_textureWidth, m_textureHeight, 0, fmt, GL_UNSIGNED_BYTE, image); glDisable(GL_TEXTURE_RECTANGLE_ARB); delete [] image; clearCaption(); m_imagePresent = true; }
void QRecordBasedSimFile::serverFileInfo ( const QString& reqid, int size, int recordSize ) { if ( reqid == d->reqid ) emit fileInfo( ( recordSize ? ( size / recordSize ) : 0 ), recordSize ); }
void ChartDialog::doExportData() { logMessage("ChartDialog::doExportData()"); QSettings settings; QString dir = settings.value("General/LastDataDir").toString(); QString selectedFilter; QString fileName = QFileDialog::getSaveFileName(this, tr("Export data to file"), dir, tr("CSV files (*.csv);;Matlab/Octave script (*.m)"), &selectedFilter); if (!fileName.isEmpty()) { QString ext = (selectedFilter.contains("CSV")) ? ".csv" : ".m"; QFileInfo fileInfo(fileName); // open file for write if (fileInfo.suffix().isEmpty()) fileName = fileName + ext; QFile file(fileName); if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) { cerr << "Could not create " + fileName.toStdString() + " file." << endl; return; } QTextStream out(&file); // export // csv if (fileInfo.suffix().toLower() == "csv") { // header for (int j = 0; j < trvTable->columnCount(); j++) out << trvTable->horizontalHeaderItem(j)->text() << ";"; out << endl; // items for (int i = 0; i < trvTable->rowCount(); i++) { for (int j = 0; j < trvTable->columnCount(); j++) out << trvTable->item(i, j)->text() << ";"; out << endl; } } // m-file if (fileInfo.suffix().toLower() == "m") { // items for (int j = 0; j < trvTable->columnCount(); j++) { out << trvTable->horizontalHeaderItem(j)->text().replace(" ", "_") << " = ["; for (int i = 0; i < trvTable->rowCount(); i++) out << trvTable->item(i, j)->text().replace(",", ".") << ((i <= trvTable->rowCount()-2) ? ", " : ""); out << "];" << endl; } // example out << endl << endl; out << "% example" << endl; out << "% plot(sqrt(X.^2 + Y.^2), " << trvTable->horizontalHeaderItem(2)->text().replace(" ", "_") << ");" << endl; out << "% grid on;" << endl; out << "% xlabel('length (m)');" << endl; out << "% ylabel('" << trvTable->horizontalHeaderItem(2)->text() << "');" << endl; } if (fileInfo.absoluteDir() != tempProblemDir()) settings.setValue("General/LastDataDir", fileInfo.absolutePath()); file.close(); } }
void CProject::setMainSourceDepend(const QStringList &list) { update(); // 首先根据list中依赖关系修改原来的依赖关系, 然后将list中没有包含的mainSource的依赖关系重置为all QStringList resetedDepend; // 根据list中依赖关系修改原来的依赖关系 QStringList dependList = list; QStringList::const_iterator constIterator = dependList.constBegin(); QStringList::const_iterator endIterator = dependList.constEnd(); // 分析组内的依赖关系, 保存在dependMap中 while (constIterator != endIterator) { // 将组内文件名保存在childList中 QStringList childList = (*constIterator).split(QRegExp("\\s+"), QString::SkipEmptyParts); // 如果组内的单词个数小于2, 则无效, 放弃它处理下一个. if (childList.count() < 2) { ++constIterator; continue; } // 主内第一个名称是main文件的依赖方式标志, "all"表示所有, "only"表示不依赖其它源文件, "part"标示依赖指定的源文件 QString mode = childList.at(0).toLower(); if (!(mode == "all" || mode == "part" || mode == "only")) { ++constIterator; continue; } // 组内的第二个文件名是含main() 的源文件, 保存在mainSource中 QString mainSource = childList.at(1); mainSource.remove(QRegExp("^./")); // 如果mainSourceList 中没有该mainSource, 则放弃该mainSource处理下一个. if (!mainSourceList.contains(mainSource)) { ++constIterator; continue; } resetedDepend << mainSource; // 标记不需要重置为依赖"all" // 若mode = "part", 则它依赖于指定的源文件, dependSources, 为 "part" 和 mainSource后面的文件 // 若mode = "only", 则它不依赖于任何其它源文件, dependSources为"only"; // 若mode 不是上面两种情况, 则保持mainSourceDependMap中原来的值"all" QFileInfo fileInfo(mainSource); QString executeFile = fileInfo.path() + "/" + fileInfo.completeBaseName(); executeFile.remove(QRegExp("^./")); if (mode == "part") { QStringList dependSources; QStringList objects; dependSources << "part"; objects << "part" << executeFile + ".o"; QString source = QString(); QString object = QString(); int count = childList.count(); int i = 2; while (i < count) { source = childList.at(i); source.remove(QRegExp("^./")); dependSources << source; fileInfo.setFile(source); object = fileInfo.path() + "/" + fileInfo.completeBaseName() + ".o"; object.remove(QRegExp("^./")); objects << object; ++i; } mainSourceDependMap[mainSource] = dependSources; executeFileDependMap[executeFile] = objects; } else if (mode == "only") { mainSourceDependMap[mainSource] = QStringList() << "only"; executeFileDependMap[executeFile] = QStringList() << "only" << executeFile + ".o"; } else { mainSourceDependMap[mainSource] = QStringList() << "all"; executeFileDependMap[executeFile] = QStringList() << "all" << executeFile + ".o"; } ++constIterator; } // 将list中没有包含的mainSource的依赖关系重置为all constIterator = mainSourceList.constBegin(); endIterator = mainSourceList.constEnd(); while (constIterator != endIterator) { if (!resetedDepend.contains(*constIterator)) { mainSourceDependMap[*constIterator] = QStringList() << "all"; QFileInfo fileInfo(*constIterator); QString executeFile = fileInfo.path() + "/" + fileInfo.completeBaseName(); executeFile.remove(QRegExp("./")); executeFileDependMap[executeFile] = QStringList() << "all" << executeFile + ".o"; } ++constIterator; } // 将新的设置转化为字符串, 并写入settings中 QString mainSourceDependValue = QString(); constIterator = mainSourceList.constBegin(); endIterator = mainSourceList.constEnd(); while (constIterator != endIterator) { QStringList list = mainSourceDependMap[*constIterator]; mainSourceDependValue += list.at(0); mainSourceDependValue += " " + *constIterator + " "; list.removeAt(0); mainSourceDependValue += list.join(" ") + ":"; ++constIterator; } mainSourceDependValue.remove(QRegExp(":$")); settings->setValue("MainSourceDepend", mainSourceDependValue); settings->sync(); settingsFileInfo.refresh(); lastUpdateTime = settingsFileInfo.lastModified(); emit updated(nameStr); }
void CProject::updateMainSourceDepend() { // mainSourceDependMap QString mainSourceDependValue = settings->value("MainSourceDepend").toString(); if (mainSourceDependValue.isEmpty()) return; // 将分组保存在dependList中 QStringList dependList = mainSourceDependValue.split(QRegExp("\\s*:\\s*"), QString::SkipEmptyParts); QStringList::const_iterator constIterator = dependList.constBegin(); QStringList::const_iterator endIterator = dependList.constEnd(); // 分析组内的依赖关系, 保存在dependMap中 while (constIterator != endIterator) { // 将组内文件名保存在childList中 QStringList childList = (*constIterator).split(QRegExp("\\s+"), QString::SkipEmptyParts); // 如果组内的单词个数小于2, 则无效, 放弃它处理下一个. if (childList.count() < 2) { ++constIterator; continue; } // 主内第一个名称是main文件的依赖方式标志, "all"表示所有, "only"表示不依赖其它源文件, "part"标示依赖指定的源文件 QString mode = childList.at(0); // 组内的第二个文件名是含main() 的源文件, 保存在mainSource中 QString mainSource = childList.at(1); mainSource.remove(QRegExp("^./")); // 如果mainSourceList 中没有该mainSource, 则放弃该mainSource处理下一个. if (!mainSourceList.contains(mainSource)) { ++constIterator; continue; } // 若mode = "only", 则它不依赖于任何其它源文件, dependSources为"only"; // 若mode = "part", 则它依赖于指定的源文件, dependSources, 为 "part" 和 mainSource后面的文件 // 若mode 不是上面两种情况, 则保持mainSourceDependMap中原来的值"all" QFileInfo fileInfo(mainSource); QString executeFile = fileInfo.path() + "/" + fileInfo.completeBaseName(); executeFile.remove(QRegExp("^./")); if (mode == "only") { mainSourceDependMap[mainSource] = QStringList() << "only"; executeFileDependMap[executeFile].removeAt(0); executeFileDependMap[executeFile].insert(0, "only"); } else if (mode == "part") { QStringList dependSources; QStringList objects; dependSources << "part"; objects << "part" << executeFile + ".o"; QString source = QString(); QString object = QString(); int count = childList.count(); int i = 2; while (i < count) { source = childList.at(i); source.remove(QRegExp("^./")); dependSources << source; fileInfo.setFile(source); object = fileInfo.path() + "/" + fileInfo.completeBaseName() + ".o"; object.remove(QRegExp("^./")); objects << object; ++i; } mainSourceDependMap[mainSource] = dependSources; executeFileDependMap[executeFile] = objects; } ++constIterator; } }
void CommandLineUtility::parseArguments(QStringList& arguments) { QStringListIterator iter(arguments); //QTextStream out(stdout); //QTextStream errorsteam(stderr); while (iter.hasNext() && !encounteredError) { QString temp = iter.next(); if (helpRegexp.exactMatch(temp)) { helpRequest = true; } else if (versionRegexp.exactMatch(temp)) { versionRequest = true; } else if (trayRegexp.exactMatch(temp)) { launchInTray = true; hideTrayIcon = false; } else if (noTrayRegexp.exactMatch(temp)) { hideTrayIcon = true; launchInTray = false; } else if (loadProfileRegexp.exactMatch(temp)) { if (iter.hasNext()) { temp = iter.next(); QFileInfo fileInfo(temp); if (fileInfo.exists()) { if (fileInfo.suffix() != "amgp" && fileInfo.suffix() != "xml") { setErrorMessage(tr("Profile location %1 is not an XML file.").arg(temp)); //errorsteam << tr("Profile location %1 is not an XML file.").arg(temp) << endl; //encounteredError = true; } else { profileLocation = fileInfo.absoluteFilePath(); } } else { setErrorMessage(tr("Profile location %1 does not exist.").arg(temp)); //errorsteam << tr("Profile location %1 does not exist.").arg(temp) << endl; //encounteredError = true; } } } else if (loadProfileForControllerRegexp.exactMatch(temp)) { if (iter.hasNext()) { temp = iter.next(); bool validNumber = false; int tempNumber = temp.toInt(&validNumber); if (validNumber) { controllerNumber = tempNumber; } else if (!temp.isEmpty()) { controllerIDString = temp; } else { setErrorMessage(tr("Controller identifier is not a valid value.")); //errorsteam << tr("Controller identifier is not a valid value.") << endl; //encounteredError = true; } } } else if (hiddenRegexp.exactMatch(temp)) { hiddenRequest = true; } else if (unloadRegexp.exactMatch(temp)) { unloadProfile = true; profileLocation = ""; if (iter.hasNext()) { temp = iter.next(); if (!isPossibleCommand(temp)) { // A value has been passed. Attempt // to validate the value. bool validNumber = false; int tempNumber = temp.toInt(&validNumber); if (validNumber) { controllerNumber = tempNumber; } else if (!temp.isEmpty()) { controllerIDString = temp; } else { setErrorMessage(tr("Controller identifier is not a valid value.")); //errorsteam << tr("Controller identifier is not a valid value.") << endl; //encounteredError = true; } } else { // Grabbed a possible command-line option. // Move iterator back to previous item. iter.previous(); } } } else if (startSetRegexp.exactMatch(temp)) { if (iter.hasNext()) { temp = iter.next(); bool validNumber = false; int tempNumber = temp.toInt(&validNumber); if (validNumber && tempNumber >= 1 && tempNumber <= 8) { startSetNumber = tempNumber; } else if (validNumber) { setErrorMessage(tr("An invalid set number was specified.")); //errorsteam << tr("An invalid set number was specified.") << endl; //encounteredError = true; } if (iter.hasNext()) { temp = iter.next(); if (!isPossibleCommand(temp)) { if (validNumber) { controllerNumber = tempNumber; } else if (!temp.isEmpty()) { controllerIDString = temp; } else { setErrorMessage(tr("Controller identifier is not a valid value.")); //errorsteam << tr("Controller identifier is not a valid value.") << endl; //encounteredError = true; } } else { // Grabbed a possible command-line option. // Move iterator back to previous item. iter.previous(); } } } else { setErrorMessage(tr("No set number was specified.")); //errorsteam << tr("No set number was specified.") << endl; //encounteredError = true; } } #ifdef USE_SDL_2 else if (gamepadListRegexp.exactMatch(temp)) { listControllers = true; } else if (mappingRegexp.exactMatch(temp)) { if (iter.hasNext()) { temp = iter.next(); bool validNumber = false; int tempNumber = temp.toInt(&validNumber); if (validNumber) { controllerNumber = tempNumber; mappingController = true; } else if (!temp.isEmpty()) { controllerIDString = temp; mappingController = true; } else { setErrorMessage(tr("Controller identifier is not a valid value.")); //errorsteam << tr("Controller identifier is not a valid value.") << endl; //encounteredError = true; } } else { setErrorMessage(tr("No controller was specified.")); //errorsteam << tr("No controller was specified.") << endl; //encounteredError = true; } } #endif #ifdef Q_OS_UNIX else if (daemonRegexp.exactMatch(temp)) { daemonMode = true; } #ifdef WITH_X11 else if (displayRegexp.exactMatch(temp)) { if (iter.hasNext()) { displayString = iter.next(); } else { setErrorMessage(tr("No display string was specified.")); //errorsteam << tr("No display string was specified.") << endl; //encounteredError = true; } } #endif #endif #if (defined (Q_OS_UNIX) && defined(WITH_UINPUT) && defined(WITH_XTEST)) \ || (defined(Q_OS_WIN) && defined(WITH_VMULTI)) else if (eventgenRegexp.exactMatch(temp)) { if (iter.hasNext()) { QString temp = iter.next(); if (!eventGeneratorsList.contains(temp)) { eventGenerator = ""; setErrorMessage(tr("An invalid event generator was specified.")); //errorsteam << tr("An invalid event generator was specified.") << endl; //encounteredError = true; } else { eventGenerator = temp; } } else { setErrorMessage(tr("No event generator string was specified.")); //errorsteam << tr("No event generator string was specified.") << endl; //encounteredError = true; } } #endif else if (qtStyleRegexp.exactMatch(temp)) { if (iter.hasNext()) { // Skip over argument iter.next(); } else { setErrorMessage(tr("Qt style flag was detected but no style was specified.")); //errorsteam << tr("Qt style flag was detected but no style was specified.") << endl; //encounteredError = true; } } else if (logLevelRegexp.exactMatch(temp)) { if (iter.hasNext()) { QString temp = iter.next(); if (temp == "debug") { currentLogLevel = Logger::LOG_DEBUG; } else if (temp == "info") { currentLogLevel = Logger::LOG_INFO; } /*else if (temp == "warn") { currentLogLevel = Logger::LOG_WARNING; } else if (temp == "error") { currentLogLevel = Logger::LOG_ERROR; } */ } else { setErrorMessage(tr("No log level specified.")); //errorsteam << tr("No log level specified.") << endl; //encounteredError = true; } } else if (isPossibleCommand(temp)) { // Flag is unrecognized. Assume that it is a Qt option. if (iter.hasNext()) { // Check next argument QString nextarg = iter.next(); if (isPossibleCommand(nextarg)) { // Flag likely didn't take an argument. Move iterator // back. iter.previous(); } } } // Check if this is the last argument. If it is and no command line flag // is active, the final argument is likely a profile that has // been specified. else if (!temp.isEmpty() && !iter.hasNext()) { // If the file exists and it is an xml file, assume that it is a // profile. QFileInfo fileInfo(temp); if (fileInfo.exists()) { if (fileInfo.suffix() != "amgp" && fileInfo.suffix() != "xml") { setErrorMessage(tr("Profile location %1 is not an XML file.").arg(temp)); //errorsteam << tr("Profile location %1 is not an XML file.").arg(temp) << endl; //encounteredError = true; } else { profileLocation = fileInfo.absoluteFilePath(); } } else { setErrorMessage(tr("Profile location %1 does not exist.").arg(temp)); //errorsteam << tr("Profile location %1 does not exist.").arg(temp) << endl; //encounteredError = true; } } } }
int MainWindow::gotText() { QString name = this->findName(ui->numberEntry->text().toInt()); ui->numberEntry->setText(""); if(name==NULL) { ui->log->append("Invalid ID: Please try again"); return 0; } Student *currStudent = findStudent(name); //gets the student object name = currStudent->getName(); //really redundant fix soon please QString time = (QTime::currentTime().toString()); //int date = (const int QDate::month()); QString date = QDate::currentDate().toString(); if (!currStudent->isSignedIn()) { //if the user is not signed in currStudent->setSignedIn(true); //sign him in ui->log->append("Signed in: " + name); currStudent->getLastSignIn()->start(); //and start the timer for how long he is there QFile file("data.csv"); QFileInfo fileInfo("data.csv"); //ui->log->append(fileInfo.absoluteFilePath()); if (file.open(QFile::WriteOnly|QFile::Append)) { QTextStream stream(&file); stream << name << "," << time <<"," << "Sign In," << date << "\r\n"; // this writes first line with two columns file.close(); } else { ui->log->append("This shit don't work"); } } else if (currStudent->isSignedIn()) { //if the user is signed in currStudent->setSignedIn(false); //sign him out int elapsed = currStudent->getLastSignIn()->elapsed(); //magically get the numbers for how long he has been there int seconds = (int) (elapsed / 1000) % 60 ; int minutes = (int) ((elapsed / (1000*60)) % 60); int hours = (int) ((elapsed / (1000*60*60)) % 24); ui->log->append("Signed out: " + name + " || Duration: " + QString::number(hours)+ ":" + QString::number(minutes) + ":" + QString::number(seconds)); //display it to him currStudent->getLastSignIn()->restart(); //and restart the timer? QFile file("data.csv"); if (file.open(QFile::WriteOnly|QFile::Append)) { QTextStream stream(&file); stream << name << "," << time <<"," << "Sign Out," << date << "\r\n"; // this writes first line with two columns file.close(); } //if(currStudent->getLastSignIn()->elapsed()==0 || (currStudent->getCorrectSignIn() && currStudent->getLastSignIn()->elapsed()>57600000)) // { // currStudent->setCorrectSignOut(false); // ui->log->append("Signed in: " + name); // currStudent->getLastSignIn()->start(); // } // else if(!currStudent->getCorrectSignIn() && currStudent->getLastSignIn()->elapsed()>57600000)//57600000 //16 hours in millesonds // { // currStudent->setCorrectSignOut(false); // ui->log->append("You did not sign-out last time, resigning-in"); // ui->log->append("Signed in: " + name); // currStudent->getLastSignIn()->restart(); // } // else if(currStudent->getLastSignIn()->elapsed()<5400000)//5400000 //1 hour 30 minutes in seconds // { // int elapsed = currStudent->getLastSignIn()->elapsed(); // int seconds = (int) (elapsed / 1000) % 60 ; // int minutes = (int) ((elapsed / (1000*60)) % 60); // int hours = (int) ((elapsed / (1000*60*60)) % 24); // ui->log->append("Signed out: " + name + " || Duration: " + QString::number(hours)+ ":" + QString::number(minutes) + ":" + QString::number(seconds)); // currStudent->getLastSignIn()->restart(); // } // else if(currStudent->getLastSignIn()->elapsed()>5400000) // { // currStudent->setCorrectSignOut(true); // int elapsed = currStudent->getLastSignIn()->elapsed(); // int seconds = (int) (elapsed / 1000) % 60 ; // int minutes = (int) ((elapsed / (1000*60)) % 60); // int hours = (int) ((elapsed / (1000*60*60)) % 24); // ui->log->append("Signed out: " + name + " || Duration: " + QString::number(hours)+ ":" + QString::number(minutes) + ":" + QString::number(seconds)); // currStudent->getLastSignIn()->restart(); // this->manager->changeStatus(name); // } } return 1; }
void SourceManager::recordSourcedFile(const FilePath& filePath, bool local) { SourcedFileInfo fileInfo(filePath.lastWriteTime(), local); sourcedFiles_[filePath.absolutePath()] = fileInfo ; }
static QString getParentPath(const QString & path) { QFileInfo fileInfo(path); return fileInfo.absolutePath(); }
QString FileUtils::getFileBaseName(const QString & filePath) { QFileInfo fileInfo(filePath); return fileInfo.completeBaseName(); }
QString BusinessLogic::StatisticsFacade::makeReport(QTextDocument* _scenario, const BusinessLogic::StatisticsParameters& _parameters) { QString result; switch (_parameters.type) { default: case StatisticsParameters::Report: { // // Определим отчёт // AbstractReport* report = 0; switch (_parameters.reportType) { default: case StatisticsParameters::SummaryReport: { report = new SummaryReport; break; } case StatisticsParameters::SceneReport: { report = new SceneReport; break; } case StatisticsParameters::LocationReport: { report = new LocationReport; break; } case StatisticsParameters::CastReport: { report = new CastReport; break; } case StatisticsParameters::CharacterReport: { report = new CharacterReport; break; } } // // Формируем отчёт // result.append("<div style=\"margin-left: 10px; margin-top: 10px; margin-right: 10px; margin-bottom: 10px;\">"); QString scenarioName = DataStorageLayer::StorageFacade::scenarioDataStorage()->name(); if (scenarioName.isEmpty()) { QFileInfo fileInfo(DatabaseLayer::Database::currentFile()); scenarioName = fileInfo.completeBaseName(); } result.append( QString("<table width=\"100%\"><tr><td><b>%1</b><br/><b>%2</b></td>" "<td valign=\"top\" align=\"right\"><small>%3 %4</small></td></tr></table>") .arg(scenarioName) .arg(report->reportName(_parameters)) .arg(QApplication::translate("BusinessLogic::ReportFacade", "generated")) .arg(QDateTime::currentDateTime().toString("dd.MM.yyyy hh:mm:ss t")) ); result.append("<hr width=\"100%\"></hr>"); result.append(report->makeReport(_scenario, _parameters)); result.append("</div>"); delete report; report = 0; break; } } return result; }
void MusicSearchEngine::watchForChanges() { qDebug() << Q_FUNC_INFO; // Gather all folders registered on music locations QFileInfoList dirs; for (QString musicPath : SettingsPrivate::instance()->musicLocations()) { QFileInfo location(musicPath); QDirIterator it(location.absoluteFilePath(), QDir::Dirs | QDir::Hidden | QDir::NoDotAndDotDot, QDirIterator::Subdirectories); while (it.hasNext()) { QString entry = it.next(); QFileInfo qFileInfo(entry); dirs << qFileInfo; } } SqlDatabase db; db.open(); db.exec("PRAGMA journal_mode = MEMORY"); db.exec("PRAGMA synchronous = OFF"); db.exec("PRAGMA temp_store = 2"); db.exec("PRAGMA foreign_keys = 1"); QStringList newFoldersToAddInLibrary; // Add folders that were not found first for (QFileInfo f : dirs) { QSqlQuery query(db); query.setForwardOnly(true); query.prepare("SELECT * FROM filesystem WHERE path = ?"); query.addBindValue(f.absoluteFilePath()); if (query.exec() && !query.next()) { newFoldersToAddInLibrary << f.absoluteFilePath(); QSqlQuery prepared(db); prepared.setForwardOnly(true); prepared.prepare("INSERT INTO filesystem (path, lastModified) VALUES (?, ?)"); prepared.addBindValue(f.absoluteFilePath()); prepared.addBindValue(f.lastModified().toTime_t()); prepared.exec(); } } if (!newFoldersToAddInLibrary.isEmpty()) { _delta = newFoldersToAddInLibrary; this->doSearch(); } // Process in reverse mode to clean cache: from database file and check if entry exists in database QSqlQuery cache("SELECT * FROM filesystem", db); qDebug() << Q_FUNC_INFO << "SELECT * FROM filesystem"; cache.setForwardOnly(true); if (cache.exec()) { QStringList oldLocations; while (cache.next()) { QDir d(cache.record().value(0).toString()); d.exists(); QFileInfo fileInfo(cache.record().value(0).toString()); // Remove folder in database because it couldn't be find in the filesystem if (!fileInfo.exists()) { QSqlQuery deleteFromFilesystem(db); deleteFromFilesystem.prepare("DELETE FROM filesystem WHERE path = ?"); deleteFromFilesystem.addBindValue(fileInfo.absoluteFilePath()); qDebug() << Q_FUNC_INFO << "DELETE FROM filesystem WHERE path = ?"; if (deleteFromFilesystem.exec()) { oldLocations << fileInfo.absoluteFilePath(); } } } qDebug() << Q_FUNC_INFO << oldLocations; if (!oldLocations.isEmpty()) { //db.rebuildFomLocations(oldLocations, QStringList()); setDelta(oldLocations); db.rebuild(); } } }
void AddMethodDialog::accept() { m_cppSupport->partController() ->editDocument( KURL( m_klass->fileName() ) ); KTextEditor::EditInterface* editIface = dynamic_cast<KTextEditor::EditInterface*>( m_cppSupport->partController() ->activePart() ); if ( !editIface ) { /// @todo show messagebox QDialog::accept(); return ; } int line, column; m_klass->getEndPosition( &line, &column ); // compute the insertion point map QMap<QString, QPair<int, int> > points; QStringList accessList; const FunctionList functionList = m_klass->functionList(); for ( FunctionList::ConstIterator it = functionList.begin(); it != functionList.end(); ++it ) { int funEndLine, funEndColumn; ( *it ) ->getEndPosition( &funEndLine, &funEndColumn ); QString access = accessID( *it ); QPair<int, int> funEndPoint = qMakePair( funEndLine, funEndColumn ); if ( !points.contains( access ) || points[ access ] < funEndPoint ) { accessList.remove( access ); accessList.push_back( access ); // move 'access' at the end of the list points[ access ] = funEndPoint; } } int insertedLine = 0; accessList += newAccessList( accessList ); for ( QStringList::iterator it = accessList.begin(); it != accessList.end(); ++it ) { QListViewItem* item = methods->firstChild(); while ( item ) { QListViewItem * currentItem = item; item = item->nextSibling(); if ( currentItem->text( 1 ) != *it ) continue; QString access = ( *it ).lower(); bool isInline = currentItem->text( 0 ) == "True"; QString str = isInline ? functionDefinition( currentItem ) : functionDeclaration( currentItem ); QPair<int, int> pt; if ( points.contains( *it ) ) { pt = points[ *it ]; } else { str.prepend( access + ":\n" ); points[ *it ] = qMakePair( line - 1, 0 ); pt = points[ *it ]; // end of class declaration } editIface->insertText( pt.first + insertedLine + 1, 0 /*pt.second*/, str ); insertedLine += str.contains( QChar( '\n' ) ); } } m_cppSupport->backgroundParser() ->addFile( m_klass->fileName() ); QString str; QListViewItem* item = methods->firstChild(); while ( item ) { QListViewItem * currentItem = item; item = item->nextSibling(); QString str = functionDefinition( currentItem ); if ( str.isEmpty() ) continue; QString implementationFile = currentItem->text( 5 ); if ( currentItem->text( 0 ) == "True" ) implementationFile = m_klass->fileName(); QFileInfo fileInfo( implementationFile ); if ( !QFile::exists( fileInfo.absFilePath() ) ) { if ( KDevCreateFile * createFileSupp = m_cppSupport->extension<KDevCreateFile>( "KDevelop/CreateFile" ) ) createFileSupp->createNewFile( fileInfo.extension(), fileInfo.dirPath( true ), fileInfo.baseName() ); } m_cppSupport->partController() ->editDocument( KURL( implementationFile ) ); editIface = dynamic_cast<KTextEditor::EditInterface*>( m_cppSupport->partController() ->activePart() ); if ( !editIface ) continue; bool isInline = currentItem->text( 0 ) == "True"; if ( !isInline ) { editIface->insertLine( editIface->numLines(), QString::fromLatin1( "" ) ); editIface->insertText( editIface->numLines() - 1, 0, str ); m_cppSupport->backgroundParser() ->addFile( implementationFile ); } } QDialog::accept(); }
bool OgreMeshAsset::DeserializeFromData(const u8 *data_, size_t numBytes, bool allowAsynchronous) { PROFILE(OgreMeshAsset_LoadFromFileInMemory); /// Force an unload of this data first. Unload(); /// @todo Duplicate allowAsynchronous code in OgreMeshAsset and TextureAsset. if ((OGRE_THREAD_SUPPORT == 0) || !assetAPI->Cache() || assetAPI->IsHeadless() || IsAssimpFileType() || assetAPI->GetFramework()->HasCommandLineParameter("--noAsyncAssetLoad") || assetAPI->GetFramework()->HasCommandLineParameter("--no_async_asset_load")) /**< @todo Remove support for the deprecated underscore version at some point. */ { allowAsynchronous = false; } QString cacheDiskSource; if (allowAsynchronous) { cacheDiskSource = assetAPI->Cache()->FindInCache(Name()); if (cacheDiskSource.isEmpty()) allowAsynchronous = false; } // Asynchronous loading // 1. AssetAPI allows a asynch load. This is false when called from LoadFromFile(), LoadFromCache() etc. // 2. We have a rendering window for Ogre as Ogre::ResourceBackgroundQueue does not work otherwise. Its not properly initialized without a rendering window. // 3. The Ogre we are building against has thread support. if (allowAsynchronous) { // We can only do threaded loading from disk, and not any disk location but only from asset cache. // local:// refs will return empty string here and those will fall back to the non-threaded loading. // Do not change this to do DiskCache() as that directory for local:// refs will not be a known resource location for ogre. QFileInfo fileInfo(cacheDiskSource); std::string sanitatedAssetRef = fileInfo.fileName().toStdString(); //! \todo - Should we set this somewhere for async path?: ogreMesh->setAutoBuildEdgeLists(false); loadTicket_ = Ogre::ResourceBackgroundQueue::getSingleton().load(Ogre::MeshManager::getSingleton().getResourceType(), sanitatedAssetRef, OgreRenderer::OgreRenderingModule::CACHE_RESOURCE_GROUP, false, 0, 0, this); return true; } if (!data_) { LogError("OgreMeshAsset::DeserializeFromData: Cannot deserialize from null input data"); return false; } // Synchronous loading if (ogreMesh.isNull()) { ogreMesh = Ogre::MeshManager::getSingleton().createManual( AssetAPI::SanitateAssetRef(this->Name()).toStdString(), Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); if (ogreMesh.isNull()) { LogError("OgreMeshAsset::DeserializeFromData: Failed to create mesh " + Name()); return false; } ogreMesh->setAutoBuildEdgeLists(false); } // Convert file to Ogre mesh using assimp if (IsAssimpFileType()) { #ifdef ASSIMP_ENABLED emit ExternalConversionRequested(this, data_, numBytes); return true; #else LogError(QString("OgreMeshAsset::DeserializeFromData: cannot convert " + Name() + " to Ogre mesh. OpenAssetImport is not enabled.")); return false; #endif } try { std::vector<u8> tempData(data_, data_ + numBytes); #include "DisableMemoryLeakCheck.h" Ogre::DataStreamPtr stream(new Ogre::MemoryDataStream((void*)&tempData[0], numBytes, false)); #include "EnableMemoryLeakCheck.h" Ogre::MeshSerializer serializer; serializer.importMesh(stream, ogreMesh.getPointer()); // Note: importMesh *adds* submeshes to an existing mesh. It doesn't replace old ones. } catch (Ogre::Exception &e) { LogError(QString("OgreMeshAsset::DeserializeFromData: Ogre::MeshSerializer::importMesh failed when loading asset '" + Name() + "': ") + e.what()); if(IsAssimpFileType()) LogError(QString("OgreMeshAsset::DeserializeFromData: cannot convert " + Name() + " to Ogre mesh. OpenAssetImport is not enabled.")); return false; } if (GenerateMeshData()) { // We did a synchronous load, must call AssetLoadCompleted here. assetAPI->AssetLoadCompleted(Name()); return true; } else return false; }
/** * Checks if file of trashItem exists in the filesystem and is readable * * @return bool */ bool TrashItem::fileExists() { QFile file(fullFilePath()); QFileInfo fileInfo(file); return file.exists() && fileInfo.isFile() && fileInfo.isReadable(); }
void MainWindow::importDeckFromXML() { QStringList filenames = QFileDialog::getOpenFileNames(0, "Import decks from xml", QDir::homePath(), "Decks (*.deck)"); if (!filenames.empty()) { bool yesToAll = false; bool noToAll = false; QStringList decksWithIssues; for (const QString& filename : filenames) { QStringList errors; QFile importFile(filename); if (importFile.open(QIODevice::ReadOnly | QIODevice::Text)) { QFileInfo fileInfo(filename); QString newFilename = Settings::instance().getDecksDir() + QDir::separator() + fileInfo.baseName() + ".deck"; if (QFileInfo(newFilename).exists()) { errors << ("Deck '" + fileInfo.baseName() + "' already exists"); } Deck deck; deck.setActive(false); QXmlStreamReader xml(&importFile); while (!xml.atEnd()) { xml.readNext(); if (xml.isStartElement() && xml.name().compare(QString("card")) == 0) { QString set = xml.attributes().value("edition").toString(); int qty = xml.attributes().value("deck").toInt(); int sb = xml.attributes().value("sb").toInt(); QString name = xml.readElementText(); if (name.contains("/")) { name = name.split("/").first(); } int dataRowIndex = mtg::CardData::instance().findRowFast(set, name); if (dataRowIndex != -1) { deck.setQuantity(dataRowIndex, qty); deck.setSideboard(dataRowIndex, sb); } else { errors << (set + " " + name + " not found"); } } if (xml.hasError()) { errors << xml.errorString(); } } bool ok = true; if (!errors.empty()) { decksWithIssues << fileInfo.baseName(); if (!yesToAll && !noToAll) { QMessageBox msgBox; msgBox.setWindowTitle("Issues"); msgBox.setText("There were some issues importing deck <i>" + fileInfo.baseName() + "</i>. Do you want to continue to import this deck?"); msgBox.setInformativeText("See details to see the issues."); msgBox.setDetailedText(errors.join("\n")); msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No | QMessageBox::YesToAll | QMessageBox::NoToAll); msgBox.setDefaultButton(QMessageBox::NoToAll); msgBox.setIcon(QMessageBox::Warning); int ret = msgBox.exec(); if (ret == QMessageBox::No) { ok = false; } if (ret == QMessageBox::NoToAll) { noToAll = true; } if (ret == QMessageBox::YesToAll) { yesToAll = true; } } if (noToAll) { ok = false; } } if (ok) { deck.save(newFilename); deckWindow_.openDeck(newFilename); } } } if (!decksWithIssues.empty()) { QMessageBox msgBox; msgBox.setWindowTitle("Decks with issues"); msgBox.setText("There were some decks with import issues."); msgBox.setInformativeText("See details to see which decks had issues."); msgBox.setDetailedText(decksWithIssues.join("\n")); msgBox.setStandardButtons(QMessageBox::Ok); msgBox.setDefaultButton(QMessageBox::Ok); msgBox.setIcon(QMessageBox::Warning); msgBox.exec(); } else { QMessageBox::information(0, "Success", "All decks were imported successfully."); } } }
QFrame * ProgramTab::createFooter() { QFrame * footerFrame = new QFrame(); footerFrame->setObjectName("footer"); // Used for styling footerFrame->setSizePolicy(QSizePolicy::Preferred,QSizePolicy::Fixed); QLabel * languageLabel = new QLabel(tr("Language:"), this); m_languageComboBox = new QComboBox(); m_languageComboBox->setEditable(false); m_languageComboBox->setEnabled(true); m_languageComboBox->addItems(m_programWindow->getAvailableLanguages()); QSettings settings; QString currentLanguage = settings.value("programwindow/language", "").toString(); if (currentLanguage.isEmpty()) { currentLanguage = m_languageComboBox->currentText(); } setLanguage(currentLanguage, false); QPushButton * addButton = new QPushButton(tr("New")); //addButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); connect(addButton, SIGNAL(clicked()), m_programWindow, SLOT(addTab())); QPushButton * loadButton = new QPushButton(tr("Open...")); //loadButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); connect(loadButton, SIGNAL(clicked()), this, SLOT(loadProgramFile())); m_saveButton = new QPushButton(tr("Save")); //m_saveButton->setSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed); connect(m_saveButton, SIGNAL(clicked()), this, SLOT(save())); QLabel * portLabel = new QLabel(tr("Port:"), this); m_portComboBox = new SerialPortComboBox(); m_portComboBox->setEditable(false); m_portComboBox->setEnabled(true); QStringList ports = m_programWindow->getSerialPorts(); m_portComboBox->addItems(ports); QString currentPort = settings.value("programwindow/port", "").toString(); if (currentPort.isEmpty()) { currentPort = m_portComboBox->currentText(); } else if (!ports.contains(currentPort)) { currentPort = m_portComboBox->currentText(); } setPort(currentPort); m_programButton = new QPushButton(tr("Program")); m_programButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); connect(m_programButton, SIGNAL(clicked()), this, SLOT(sendProgram())); m_programButton->setEnabled(false); QLabel * programmerLabel = new QLabel(tr("Programmer:"), this); m_programmerComboBox = new QComboBox(); m_programmerComboBox->setEditable(false); m_programmerComboBox->setEnabled(true); updateProgrammers(); QString currentProgrammer = ProgramWindow::LocateName; QString temp = settings.value("programwindow/programmer", "").toString(); if (!temp.isEmpty()) { QFileInfo fileInfo(temp); if (fileInfo.exists()) { currentProgrammer = temp; } } chooseProgrammerAux(currentProgrammer, false); QHBoxLayout *footerLayout = new QHBoxLayout; footerLayout->setMargin(0); footerLayout->setSpacing(5); footerLayout->addWidget(addButton); footerLayout->addWidget(loadButton); footerLayout->addWidget(m_saveButton); footerLayout->addSpacerItem(new QSpacerItem(5,0,QSizePolicy::Expanding,QSizePolicy::Minimum)); footerLayout->addWidget(languageLabel); footerLayout->addWidget(m_languageComboBox); footerLayout->addWidget(portLabel); footerLayout->addWidget(m_portComboBox); footerLayout->addWidget(programmerLabel); footerLayout->addWidget(m_programmerComboBox); footerLayout->addWidget(m_programButton); footerFrame->setLayout(footerLayout); // connect last so these signals aren't triggered during initialization connect(m_languageComboBox, SIGNAL(currentIndexChanged(const QString &)), this, SLOT(setLanguage(const QString &))); connect(m_portComboBox, SIGNAL(currentIndexChanged(const QString &)), this, SLOT(setPort(const QString &))); connect(m_portComboBox, SIGNAL(aboutToShow()), this, SLOT(updateSerialPorts()), Qt::DirectConnection); connect(m_programmerComboBox, SIGNAL(activated(int)), this, SLOT(chooseProgrammerTimed(int))); return footerFrame; }
void MainWindow::importDeckFromText() { QStringList filenames = QFileDialog::getOpenFileNames(0, "Import decks from text", QDir::homePath(), "Decks (*.txt)"); QString set = QInputDialog::getText(this, "Enter Set Code", "Set Code"); if (!filenames.empty()) { bool yesToAll = false; bool noToAll = false; QStringList decksWithIssues; for (const QString& filename : filenames) { QStringList errors; QFile importFile(filename); if (importFile.open(QIODevice::ReadOnly | QIODevice::Text)) { QFileInfo fileInfo(filename); QString newFilename = Settings::instance().getDecksDir() + QDir::separator() + fileInfo.baseName() + ".deck"; if (QFileInfo(newFilename).exists()) { errors << ("Deck '" + fileInfo.baseName() + "' already exists"); } Deck deck; deck.setActive(false); QStringList lines; QTextStream in(&importFile); while (!in.atEnd()) { lines << in.readLine(); } importFile.close(); for (int i = 0; i < lines.size(); ++i) { QTextStream stream(&lines[i]); int amount; stream >> amount; QString name = stream.readAll().trimmed(); qDebug() << "Amount" << amount; qDebug() << "Name" << name; int dataRowIndex = mtg::CardData::instance().findRowFast(set, name); if (dataRowIndex != -1) { deck.setQuantity(dataRowIndex, amount); } else { errors << (set + " " + name + " not found"); } } bool ok = true; if (!errors.empty()) { decksWithIssues << fileInfo.baseName(); if (!yesToAll && !noToAll) { QMessageBox msgBox; msgBox.setWindowTitle("Issues"); msgBox.setText("There were some issues importing deck <i>" + fileInfo.baseName() + "</i>. Do you want to continue to import this deck?"); msgBox.setInformativeText("See details to see the issues."); msgBox.setDetailedText(errors.join("\n")); msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No | QMessageBox::YesToAll | QMessageBox::NoToAll); msgBox.setDefaultButton(QMessageBox::NoToAll); msgBox.setIcon(QMessageBox::Warning); int ret = msgBox.exec(); if (ret == QMessageBox::No) { ok = false; } if (ret == QMessageBox::NoToAll) { noToAll = true; } if (ret == QMessageBox::YesToAll) { yesToAll = true; } } if (noToAll) { ok = false; } } if (ok) { deck.save(newFilename); deckWindow_.openDeck(newFilename); } } }
inline QUrl TEST_FILE(const QString &filename) { QFileInfo fileInfo(__FILE__); return QUrl::fromLocalFile(fileInfo.absoluteDir().filePath(filename)); }
QgsGrassRasterProvider::QgsGrassRasterProvider( QString const &uri ) : QgsRasterDataProvider( uri ) , mNoDataValue( std::numeric_limits<double>::quiet_NaN() ) { QgsDebugMsg( "QgsGrassRasterProvider: constructing with uri '" + uri + "'." ); if ( !QgsGrass::init() ) { return; } // Parse URI, it is the same like using GDAL, i.e. path to raster cellhd, i.e. // /path/to/gisdbase/location/mapset/cellhd/map QFileInfo fileInfo( uri ); if ( !fileInfo.exists() ) // then we keep it valid forever { appendError( ERR( tr( "cellhd file %1 does not exist" ).arg( uri ) ) ); return; } mMapName = fileInfo.fileName(); QDir dir = fileInfo.dir(); QString element = dir.dirName(); if ( element != QLatin1String( "cellhd" ) ) { appendError( ERR( tr( "Groups not yet supported" ) ) ); return; } dir.cdUp(); // skip cellhd mMapset = dir.dirName(); dir.cdUp(); mLocation = dir.dirName(); dir.cdUp(); mGisdbase = dir.path(); QgsDebugMsg( QString( "gisdbase: %1" ).arg( mGisdbase ) ); QgsDebugMsg( QString( "location: %1" ).arg( mLocation ) ); QgsDebugMsg( QString( "mapset: %1" ).arg( mMapset ) ); QgsDebugMsg( QString( "mapName: %1" ).arg( mMapName ) ); mTimestamp = dataTimestamp(); mRasterValue.set( mGisdbase, mLocation, mMapset, mMapName ); //mValidNoDataValue = true; QString error; mCrs = QgsGrass::crs( mGisdbase, mLocation, error ); appendIfError( error ); QgsDebugMsg( "mCrs: " + mCrs.toWkt() ); // the block size can change of course when the raster is overridden // ibut it is only called once when statistics are calculated error.clear(); QgsGrass::size( mGisdbase, mLocation, mMapset, mMapName, &mCols, &mRows, error ); appendIfError( error ); error.clear(); mInfo = QgsGrass::info( mGisdbase, mLocation, mMapset, mMapName, QgsGrassObject::Raster, QStringLiteral( "info" ), QgsRectangle(), 0, 0, 3000, error ); appendIfError( error ); mGrassDataType = mInfo[QStringLiteral( "TYPE" )].toInt(); QgsDebugMsg( "mGrassDataType = " + QString::number( mGrassDataType ) ); // TODO: avoid showing these strange numbers in GUI // TODO: don't save no data values in project file, add a flag if value was defined by user double myInternalNoDataValue; if ( mGrassDataType == CELL_TYPE ) { myInternalNoDataValue = std::numeric_limits<int>::min(); } else if ( mGrassDataType == DCELL_TYPE ) { // Don't use numeric limits, raster layer is using // std::fabs( myValue - mNoDataValue ) <= TINY_VALUE // if the mNoDataValue would be a limit, the subtraction could overflow. // No data value is shown in GUI, use some nice number. // Choose values with small representation error. // limit: 1.7976931348623157e+308 //myInternalNoDataValue = -1e+300; myInternalNoDataValue = std::numeric_limits<double>::quiet_NaN(); } else { if ( mGrassDataType != FCELL_TYPE ) { QgsDebugMsg( "unexpected data type" ); } // limit: 3.40282347e+38 //myInternalNoDataValue = -1e+30; myInternalNoDataValue = std::numeric_limits<float>::quiet_NaN(); } mNoDataValue = myInternalNoDataValue; mSrcHasNoDataValue.append( true ); mSrcNoDataValue.append( mNoDataValue ); mUseSrcNoDataValue.append( true ); QgsDebugMsg( QString( "myInternalNoDataValue = %1" ).arg( myInternalNoDataValue ) ); // TODO: refresh mRows and mCols if raster was rewritten // We have to decide some reasonable block size, not to big to occupate too much // memory, not too small to result in too many calls to readBlock -> qgis.d.rast // for statistics int typeSize = dataTypeSize( dataType( 1 ) ); if ( mCols > 0 && typeSize > 0 ) { const int cache_size = 10000000; // ~ 10 MB mYBlockSize = cache_size / typeSize / mCols; if ( mYBlockSize > mRows ) { mYBlockSize = mRows; } QgsDebugMsg( "mYBlockSize = " + QString::number( mYBlockSize ) ); mValid = true; } }
bool MainWindow2::openObject( QString strFilePath ) { QProgressDialog progress( tr("Opening document..."), tr("Abort"), 0, 100, this ); progress.setWindowModality( Qt::WindowModal ); progress.show(); editor->setCurrentLayer( 0 ); editor->layerManager()->setCurrentFrameIndex( 1 ); editor->fps = 12; m_pTimeLine->setFps( editor->fps ); m_pScribbleArea->setMyView( QMatrix() ); ObjectSaveLoader objectLoader( this ); Object* pObject = objectLoader.loadFromFile( strFilePath ); if ( pObject != NULL && objectLoader.error().code() == PCL_OK ) { SafeDelete( m_object ); m_object = pObject; pObject->setFilePath( strFilePath ); QSettings settings( "Pencil", "Pencil" ); settings.setValue( "lastFilePath", QVariant( pObject->filePath() ) ); editor->setObject( pObject ); editor->updateObject(); m_recentFileMenu->addRecentFile( pObject->filePath() ); m_recentFileMenu->saveToDisk(); qDebug() << "Current File Path=" << pObject->filePath(); setWindowTitle( pObject->filePath() ); } else { return false; } return true; //------------------- QString filePath = strFilePath; bool openingTheOLDWAY = true; QString realXMLFilePath = filePath; QString tmpFilePath; // ---- test before opening ---- QStringList zippedFileList = JlCompress::getFileList( filePath ); if ( !zippedFileList.empty() ) { qDebug() << "Recognized New zipped Pencil File Format !"; openingTheOLDWAY = false; // ---- now decompress PFF ----- QFileInfo fileInfo( filePath ); QDir dir( QDir::tempPath() ); tmpFilePath = QDir::tempPath() + "/" + fileInfo.completeBaseName() + PFF_TMP_DECOMPRESS_EXT; if ( fileInfo.exists() ) { dir.rmpath( tmpFilePath ); // --removes an old decompression directory removePFFTmpDirectory( tmpFilePath ); // --removes an old decompression directory - better approach } dir.mkpath( tmpFilePath ); // --creates a new decompression directory JlCompress::extractDir( filePath, tmpFilePath ); realXMLFilePath = tmpFilePath + "/" + PFF_XML_FILE_NAME; } else { qDebug() << "Recognized Old Pencil File Format !"; } QScopedPointer<QFile> file( new QFile( realXMLFilePath ) ); //QFile* file = new QFile(filePath); if ( !file->open( QFile::ReadOnly ) ) { if ( !openingTheOLDWAY ) { removePFFTmpDirectory( tmpFilePath ); // --removes temporary decompression directory } return false; } QDomDocument doc; if ( !doc.setContent( file.data() ) ) { if ( !openingTheOLDWAY ) { removePFFTmpDirectory( tmpFilePath ); // --removes temporary decompression directory } return false; // this is not a XML file } QDomDocumentType type = doc.doctype(); if ( type.name() != "PencilDocument" && type.name() != "MyObject" ) { if ( !openingTheOLDWAY ) { removePFFTmpDirectory( tmpFilePath ); // --removes temporary decompression directory } return false; // this is not a Pencil document } // delete old object @sent foreward -> if (ok) /*if (m_object != NULL) { m_object->deleteLater(); }*/ // ----------------------------- //QSettings settings("Pencil","Pencil"); //settings.setValue("lastFilePath", QVariant(object->strCurrentFilePath) ); QString dataLayersDir; if ( openingTheOLDWAY ) { dataLayersDir = filePath + "." + PFF_LAYERS_DIR; } else { dataLayersDir = tmpFilePath + "/" + PFF_LAYERS_DIR; } Object* newObject = new Object(); if ( !newObject->loadPalette( dataLayersDir ) ) { newObject->loadDefaultPalette(); } editor->setObject( newObject ); newObject->setFilePath( filePath ); // ------- reads the XML file ------- bool ok = true; int progVal = 0; QDomElement docElem = doc.documentElement(); if ( docElem.isNull() ) { return false; } if ( docElem.tagName() == "document" ) { qDebug( "Object Loader: start." ); qreal rProgressValue = 0; qreal rProgressDelta = 100 / docElem.childNodes().count(); QDomNode tag = docElem.firstChild(); while ( !tag.isNull() ) { QDomElement element = tag.toElement(); // try to convert the node to an element. if ( !element.isNull() ) { progVal = qMin( (int)rProgressValue, 100 ); progress.setValue( progVal ); rProgressValue += rProgressDelta; if ( element.tagName() == "editor" ) { qDebug( " Load editor" ); loadDomElement( element, filePath ); } else if ( element.tagName() == "object" ) { qDebug( " Load object" ); ok = newObject->loadDomElement( element, dataLayersDir ); qDebug() << " dataDir:" << dataLayersDir; } } tag = tag.nextSibling(); } } else { if ( docElem.tagName() == "object" || docElem.tagName() == "MyOject" ) // old Pencil format (<=0.4.3) { ok = newObject->loadDomElement( docElem, filePath ); } } // ------------------------------ if ( ok ) { editor->updateObject(); if ( !openingTheOLDWAY ) { removePFFTmpDirectory( tmpFilePath ); // --removes temporary decompression directory } m_recentFileMenu->addRecentFile( filePath ); m_recentFileMenu->saveToDisk(); //qDebug() << "Current File Path=" << newObject->strCurrentFilePath; setWindowTitle( newObject->filePath() ); // FIXME: need to free the old object. but delete object will crash app, don't know why. // fixed by shoshon... don't know if it's right Object* objectToDelete = m_object; m_object = newObject; if ( objectToDelete != NULL ) { delete objectToDelete; } } progress.setValue( 100 ); return true; }
QString QStandardPaths::writableLocation(StandardLocation type) { switch (type) { case HomeLocation: return QDir::homePath(); case TempLocation: return QDir::tempPath(); case CacheLocation: case GenericCacheLocation: { // http://standards.freedesktop.org/basedir-spec/basedir-spec-0.6.html QString xdgCacheHome = QFile::decodeName(qgetenv("XDG_CACHE_HOME")); if (isTestModeEnabled()) xdgCacheHome = QDir::homePath() + QLatin1String("/.qttest/cache"); if (xdgCacheHome.isEmpty()) xdgCacheHome = QDir::homePath() + QLatin1String("/.cache"); if (type == QStandardPaths::CacheLocation) appendOrganizationAndApp(xdgCacheHome); return xdgCacheHome; } case DataLocation: case GenericDataLocation: { QString xdgDataHome = QFile::decodeName(qgetenv("XDG_DATA_HOME")); if (isTestModeEnabled()) xdgDataHome = QDir::homePath() + QLatin1String("/.qttest/share"); if (xdgDataHome.isEmpty()) xdgDataHome = QDir::homePath() + QLatin1String("/.local/share"); if (type == QStandardPaths::DataLocation) appendOrganizationAndApp(xdgDataHome); return xdgDataHome; } case ConfigLocation: { // http://standards.freedesktop.org/basedir-spec/latest/ QString xdgConfigHome = QFile::decodeName(qgetenv("XDG_CONFIG_HOME")); if (isTestModeEnabled()) xdgConfigHome = QDir::homePath() + QLatin1String("/.qttest/config"); if (xdgConfigHome.isEmpty()) xdgConfigHome = QDir::homePath() + QLatin1String("/.config"); return xdgConfigHome; } case RuntimeLocation: { const uid_t myUid = geteuid(); // http://standards.freedesktop.org/basedir-spec/latest/ QString xdgRuntimeDir = QFile::decodeName(qgetenv("XDG_RUNTIME_DIR")); if (xdgRuntimeDir.isEmpty()) { const QString userName = QFileSystemEngine::resolveUserName(myUid); xdgRuntimeDir = QDir::tempPath() + QLatin1String("/runtime-") + userName; QDir dir(xdgRuntimeDir); if (!dir.exists()) { if (!QDir().mkdir(xdgRuntimeDir)) { qWarning("QStandardPaths: error creating runtime directory %s: %s", qPrintable(xdgRuntimeDir), qPrintable(qt_error_string(errno))); return QString(); } } qWarning("QStandardPaths: XDG_RUNTIME_DIR not set, defaulting to '%s'", qPrintable(xdgRuntimeDir)); } // "The directory MUST be owned by the user" QFileInfo fileInfo(xdgRuntimeDir); if (fileInfo.ownerId() != myUid) { qWarning("QStandardPaths: wrong ownership on runtime directory %s, %d instead of %d", qPrintable(xdgRuntimeDir), fileInfo.ownerId(), myUid); return QString(); } // "and he MUST be the only one having read and write access to it. Its Unix access mode MUST be 0700." QFile file(xdgRuntimeDir); const QFile::Permissions wantedPerms = QFile::ReadUser | QFile::WriteUser | QFile::ExeUser; if (file.permissions() != wantedPerms && !file.setPermissions(wantedPerms)) { qWarning("QStandardPaths: wrong permissions on runtime directory %s", qPrintable(xdgRuntimeDir)); return QString(); } return xdgRuntimeDir; } default: break; } #ifndef QT_BOOTSTRAPPED // http://www.freedesktop.org/wiki/Software/xdg-user-dirs QString xdgConfigHome = QFile::decodeName(qgetenv("XDG_CONFIG_HOME")); if (xdgConfigHome.isEmpty()) xdgConfigHome = QDir::homePath() + QLatin1String("/.config"); QFile file(xdgConfigHome + QLatin1String("/user-dirs.dirs")); if (!isTestModeEnabled() && file.open(QIODevice::ReadOnly)) { QHash<QString, QString> lines; QTextStream stream(&file); // Only look for lines like: XDG_DESKTOP_DIR="$HOME/Desktop" QRegExp exp(QLatin1String("^XDG_(.*)_DIR=(.*)$")); while (!stream.atEnd()) { const QString &line = stream.readLine(); if (exp.indexIn(line) != -1) { const QStringList lst = exp.capturedTexts(); const QString key = lst.at(1); QString value = lst.at(2); if (value.length() > 2 && value.startsWith(QLatin1Char('\"')) && value.endsWith(QLatin1Char('\"'))) value = value.mid(1, value.length() - 2); // Store the key and value: "DESKTOP", "$HOME/Desktop" lines[key] = value; } } QString key; switch (type) { case DesktopLocation: key = QLatin1String("DESKTOP"); break; case DocumentsLocation: key = QLatin1String("DOCUMENTS"); break; case PicturesLocation: key = QLatin1String("PICTURES"); break; case MusicLocation: key = QLatin1String("MUSIC"); break; case MoviesLocation: key = QLatin1String("VIDEOS"); break; case DownloadLocation: key = QLatin1String("DOWNLOAD"); break; default: break; } if (!key.isEmpty()) { QString value = lines.value(key); if (!value.isEmpty()) { // value can start with $HOME if (value.startsWith(QLatin1String("$HOME"))) value = QDir::homePath() + value.mid(5); return value; } } } #endif QString path; switch (type) { case DesktopLocation: path = QDir::homePath() + QLatin1String("/Desktop"); break; case DocumentsLocation: path = QDir::homePath() + QLatin1String("/Documents"); break; case PicturesLocation: path = QDir::homePath() + QLatin1String("/Pictures"); break; case FontsLocation: path = QDir::homePath() + QLatin1String("/.fonts"); break; case MusicLocation: path = QDir::homePath() + QLatin1String("/Music"); break; case MoviesLocation: path = QDir::homePath() + QLatin1String("/Videos"); break; case DownloadLocation: path = QDir::homePath() + QLatin1String("/Downloads"); break; case ApplicationsLocation: path = writableLocation(GenericDataLocation) + QLatin1String("/applications"); break; default: break; } return path; }
/* The corrupted file is generated by copying a few random numbers from /dev/random on a linux machine. */ void tst_QAudioDecoderBackend::corruptedFileTest() { QAudioDecoder d; QAudioBuffer buffer; QVERIFY(d.state() == QAudioDecoder::StoppedState); QVERIFY(d.bufferAvailable() == false); QCOMPARE(d.sourceFilename(), QString("")); QVERIFY(d.audioFormat() == QAudioFormat()); // Test local file QFileInfo fileInfo(QFINDTESTDATA(TEST_CORRUPTED_FILE_NAME)); d.setSourceFilename(fileInfo.absoluteFilePath()); QVERIFY(d.state() == QAudioDecoder::StoppedState); QVERIFY(!d.bufferAvailable()); QCOMPARE(d.sourceFilename(), fileInfo.absoluteFilePath()); QSignalSpy readySpy(&d, SIGNAL(bufferReady())); QSignalSpy bufferChangedSpy(&d, SIGNAL(bufferAvailableChanged(bool))); QSignalSpy errorSpy(&d, SIGNAL(error(QAudioDecoder::Error))); QSignalSpy stateSpy(&d, SIGNAL(stateChanged(QAudioDecoder::State))); QSignalSpy durationSpy(&d, SIGNAL(durationChanged(qint64))); QSignalSpy finishedSpy(&d, SIGNAL(finished())); QSignalSpy positionSpy(&d, SIGNAL(positionChanged(qint64))); d.start(); QTRY_VERIFY(d.state() == QAudioDecoder::StoppedState); QVERIFY(!d.bufferAvailable()); QCOMPARE(d.audioFormat(), QAudioFormat()); QCOMPARE(d.duration(), qint64(-1)); QCOMPARE(d.position(), qint64(-1)); // Check the error code. QTRY_VERIFY(!errorSpy.isEmpty()); // Have to use qvariant_cast, toInt will return 0 because unrecognized type; QAudioDecoder::Error errorCode = qvariant_cast<QAudioDecoder::Error>(errorSpy.takeLast().at(0)); QCOMPARE(errorCode, QAudioDecoder::FormatError); QCOMPARE(d.error(), QAudioDecoder::FormatError); // Check all other spies. QVERIFY(readySpy.isEmpty()); QVERIFY(bufferChangedSpy.isEmpty()); QVERIFY(stateSpy.isEmpty()); QVERIFY(finishedSpy.isEmpty()); QVERIFY(positionSpy.isEmpty()); QVERIFY(durationSpy.isEmpty()); errorSpy.clear(); // Try read even if the file is corrupted to test the robustness. buffer = d.read(); QTRY_VERIFY(d.state() == QAudioDecoder::StoppedState); QVERIFY(!buffer.isValid()); QVERIFY(!d.bufferAvailable()); QCOMPARE(d.position(), qint64(-1)); QVERIFY(errorSpy.isEmpty()); QVERIFY(readySpy.isEmpty()); QVERIFY(bufferChangedSpy.isEmpty()); QVERIFY(stateSpy.isEmpty()); QVERIFY(finishedSpy.isEmpty()); QVERIFY(positionSpy.isEmpty()); QVERIFY(durationSpy.isEmpty()); d.stop(); QTRY_COMPARE(d.state(), QAudioDecoder::StoppedState); QCOMPARE(d.duration(), qint64(-1)); QVERIFY(!d.bufferAvailable()); }
// ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- int H5FilterParametersWriter::WritePipelineToFile(FilterPipeline::Pointer pipeline, QString filePath, QString name, IObserver* obs) { if (NULL == pipeline.get()) { if (NULL != obs) { PipelineMessage pm(H5FilterParametersWriter::ClassName(), "FilterPipeline Object was NULL for writing", -1, PipelineMessage::Error); obs->processPipelineMessage(pm); } return -1; } QFileInfo fileInfo(filePath); // WRITE THE PIPELINE TO THE HDF5 FILE H5FilterParametersWriter::Pointer writer = H5FilterParametersWriter::New(); hid_t fileId = -1; fileId = QH5Utilities::createFile(filePath); if (fileId < 0) { if (NULL != obs) { PipelineMessage pm(H5FilterParametersWriter::ClassName(), "Output .dream3d file could not be created.", -1, PipelineMessage::Error); obs->processPipelineMessage(pm); } return -1; } // This will make sure if we return early from this method that the HDF5 File is properly closed. // This will also take care of making sure all groups and file ids are closed // before this method returns. HDF5ScopedFileSentinel scopedFileSentinel(&fileId, true); // Write our File Version string to the Root "/" group QH5Lite::writeStringAttribute(fileId, "/", DREAM3D::HDF5::FileVersionName, DREAM3D::HDF5::FileVersion); QH5Lite::writeStringAttribute(fileId, "/", DREAM3D::HDF5::DREAM3DVersion, DREAM3DLib::Version::Complete() ); hid_t pipelineGroupId = QH5Utilities::createGroup(fileId, DREAM3D::StringConstants::PipelineGroupName); scopedFileSentinel.addGroupId(&pipelineGroupId); writer->setGroupId(pipelineGroupId); FilterPipeline::FilterContainerType& filters = pipeline->getFilterContainer(); // Loop over each filter and write it's input parameters to the file int count = filters.size(); int index = 0; for (qint32 i = 0; i < count; ++i) { AbstractFilter::Pointer filter = filters.at(i); if (NULL != filter.get()) { index = filter->writeFilterParameters(writer.get(), index); } else { AbstractFilter::Pointer badFilter = AbstractFilter::New(); writer->openFilterGroup(badFilter.get(), i); writer->writeValue("Unknown Filter", "ERROR: Filter instance was NULL within the PipelineFilterWidget instance. Report this error to the DREAM3D Developers"); writer->closeFilterGroup(); } } return 0; }
void tst_QAudioDecoderBackend::fileTest() { QAudioDecoder d; QAudioBuffer buffer; quint64 duration = 0; int byteCount = 0; int sampleCount = 0; QVERIFY(d.state() == QAudioDecoder::StoppedState); QVERIFY(d.bufferAvailable() == false); QCOMPARE(d.sourceFilename(), QString("")); QVERIFY(d.audioFormat() == QAudioFormat()); // Test local file QFileInfo fileInfo(QFINDTESTDATA(TEST_FILE_NAME)); d.setSourceFilename(fileInfo.absoluteFilePath()); QVERIFY(d.state() == QAudioDecoder::StoppedState); QVERIFY(!d.bufferAvailable()); QCOMPARE(d.sourceFilename(), fileInfo.absoluteFilePath()); QSignalSpy readySpy(&d, SIGNAL(bufferReady())); QSignalSpy bufferChangedSpy(&d, SIGNAL(bufferAvailableChanged(bool))); QSignalSpy errorSpy(&d, SIGNAL(error(QAudioDecoder::Error))); QSignalSpy stateSpy(&d, SIGNAL(stateChanged(QAudioDecoder::State))); QSignalSpy durationSpy(&d, SIGNAL(durationChanged(qint64))); QSignalSpy finishedSpy(&d, SIGNAL(finished())); QSignalSpy positionSpy(&d, SIGNAL(positionChanged(qint64))); d.start(); QTRY_VERIFY(d.state() == QAudioDecoder::DecodingState); QTRY_VERIFY(!stateSpy.isEmpty()); QTRY_VERIFY(!readySpy.isEmpty()); QTRY_VERIFY(!bufferChangedSpy.isEmpty()); QVERIFY(d.bufferAvailable()); QTRY_VERIFY(!durationSpy.isEmpty()); QVERIFY(qAbs(d.duration() - 1000) < 20); buffer = d.read(); QVERIFY(buffer.isValid()); // Test file is 44.1K 16bit mono, 44094 samples QCOMPARE(buffer.format().channelCount(), 1); QCOMPARE(buffer.format().sampleRate(), 44100); QCOMPARE(buffer.format().sampleSize(), 16); QCOMPARE(buffer.format().sampleType(), QAudioFormat::SignedInt); QCOMPARE(buffer.format().codec(), QString("audio/pcm")); QCOMPARE(buffer.byteCount(), buffer.sampleCount() * 2); // 16bit mono // The decoder should still have no format set QVERIFY(d.audioFormat() == QAudioFormat()); QVERIFY(errorSpy.isEmpty()); duration += buffer.duration(); sampleCount += buffer.sampleCount(); byteCount += buffer.byteCount(); // Now drain the decoder if (sampleCount < 44094) { QTRY_COMPARE(d.bufferAvailable(), true); } while (d.bufferAvailable()) { buffer = d.read(); QVERIFY(buffer.isValid()); QTRY_VERIFY(!positionSpy.isEmpty()); QVERIFY(positionSpy.takeLast().at(0).toLongLong() == qint64(duration / 1000)); duration += buffer.duration(); sampleCount += buffer.sampleCount(); byteCount += buffer.byteCount(); if (sampleCount < 44094) { QTRY_COMPARE(d.bufferAvailable(), true); } } // Make sure the duration is roughly correct (+/- 20ms) QCOMPARE(sampleCount, 44094); QCOMPARE(byteCount, 44094 * 2); QVERIFY(qAbs(qint64(duration) - 1000000) < 20000); QVERIFY(qAbs((d.position() + (buffer.duration() / 1000)) - 1000) < 20); QTRY_COMPARE(finishedSpy.count(), 1); QVERIFY(!d.bufferAvailable()); QTRY_COMPARE(d.state(), QAudioDecoder::StoppedState); d.stop(); QTRY_COMPARE(d.state(), QAudioDecoder::StoppedState); QTRY_COMPARE(durationSpy.count(), 2); QCOMPARE(d.duration(), qint64(-1)); QVERIFY(!d.bufferAvailable()); readySpy.clear(); bufferChangedSpy.clear(); stateSpy.clear(); durationSpy.clear(); finishedSpy.clear(); positionSpy.clear(); // change output audio format QAudioFormat format; format.setChannelCount(2); format.setSampleSize(8); format.setSampleRate(11050); format.setCodec("audio/pcm"); format.setSampleType(QAudioFormat::SignedInt); d.setAudioFormat(format); // We expect 1 second still, at 11050 * 2 samples == 22k samples. // (at 1 byte/sample -> 22kb) // Make sure it stuck QVERIFY(d.audioFormat() == format); duration = 0; sampleCount = 0; byteCount = 0; d.start(); QTRY_VERIFY(d.state() == QAudioDecoder::DecodingState); QTRY_VERIFY(!stateSpy.isEmpty()); QTRY_VERIFY(!readySpy.isEmpty()); QTRY_VERIFY(!bufferChangedSpy.isEmpty()); QVERIFY(d.bufferAvailable()); QTRY_VERIFY(!durationSpy.isEmpty()); QVERIFY(qAbs(d.duration() - 1000) < 20); buffer = d.read(); QVERIFY(buffer.isValid()); // See if we got the right format QVERIFY(buffer.format() == format); // The decoder should still have the same format QVERIFY(d.audioFormat() == format); QVERIFY(errorSpy.isEmpty()); duration += buffer.duration(); sampleCount += buffer.sampleCount(); byteCount += buffer.byteCount(); // Now drain the decoder if (duration < 998000) { QTRY_COMPARE(d.bufferAvailable(), true); } while (d.bufferAvailable()) { buffer = d.read(); QVERIFY(buffer.isValid()); QTRY_VERIFY(!positionSpy.isEmpty()); QVERIFY(positionSpy.takeLast().at(0).toLongLong() == qint64(duration / 1000)); QVERIFY(d.position() - (duration / 1000) < 20); duration += buffer.duration(); sampleCount += buffer.sampleCount(); byteCount += buffer.byteCount(); if (duration < 998000) { QTRY_COMPARE(d.bufferAvailable(), true); } } // Resampling might end up with fewer or more samples // so be a bit sloppy QVERIFY(qAbs(sampleCount - 22047) < 100); QVERIFY(qAbs(byteCount - 22047) < 100); QVERIFY(qAbs(qint64(duration) - 1000000) < 20000); QVERIFY(qAbs((d.position() + (buffer.duration() / 1000)) - 1000) < 20); QTRY_COMPARE(finishedSpy.count(), 1); QVERIFY(!d.bufferAvailable()); QTRY_COMPARE(d.state(), QAudioDecoder::StoppedState); d.stop(); QTRY_COMPARE(d.state(), QAudioDecoder::StoppedState); QTRY_COMPARE(durationSpy.count(), 2); QCOMPARE(d.duration(), qint64(-1)); QVERIFY(!d.bufferAvailable()); }
bool FileUtils::isFile(const QString &filePath) { QFileInfo fileInfo(filePath); return (fileInfo.exists() && fileInfo.isFile()); }