static bool isUpdatePossible() { if (!qApp) return false; if (!progressDialog()) return false; return progressDialog()->thread() == QThread::currentThread(); }
//-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- void ProgressInfoStatic::start(size_t maxProgressValue, const QString& title) { if (!isUpdatePossible()) return; if (!maxProgressStack().size()) { //progressDialog()->setWindowModality(Qt::ApplicationModal); progressDialog()->setMinimum(0); progressDialog()->setWindowTitle(title); progressDialog()->setCancelButton(NULL); progressDialog()->show(); } maxProgressStack().push_back(maxProgressValue); progressStack().push_back(0); progressSpanStack().push_back(1); titleStack().push_back(title); descriptionStack().push_back(""); progressDialog()->setMaximum(static_cast<int>(currentTotalMaxProgressValue())); progressDialog()->setValue(static_cast<int>(currentTotalProgress())); progressDialog()->setLabelText(currentComposedLabel()); //QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents); if (progressDialog()) progressDialog()->repaint(); }
//-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- void ProgressInfoStatic::setProgressDescription(const QString& description) { if (!isUpdatePossible()) return; descriptionStack().back() = description; progressDialog()->setLabelText(currentComposedLabel()); //QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents); if (progressDialog()) progressDialog()->repaint(); }
/* on_backupButton_clicked() * Called : When User Clicks Backup Button * Performs : Bakeup of Log */ void Settings::on_backupButton_clicked() { if(logPathLE->text().isEmpty()) return; directory=logPathLE->text()+"DocmaQ Log Backup/"; QStringList logpath,logdir; QString path,dir; logpath<<"./logs/certificate/"<<"./logs/session/"; logdir<<"certificate"<<"session"; int q=0; for(int k=0;k<2;k++) { path=logpath[k]; dir=logdir[k]; QDir logDir(path); QStringList files = logDir.entryList(QStringList("*.Log"),QDir::Files,QDir::Time|QDir::Reversed); uint size=files.count(); if(!QDir(directory+dir).exists()) { QDir().mkdir(directory); //create a directory if dir doesn't exist QDir().mkdir(directory+dir); } QProgressDialog progressDialog(this); progressDialog.setCancelButtonText(tr("&Cancel")); progressDialog.setRange(0, size); progressDialog.setWindowTitle(tr("Performing Back Up.... ")); progressDialog.show(); for (uint i=0;i<size;i++) { q=1; progressDialog.setValue(i); progressDialog.setLabelText(tr("Back up file %1 of %2...\n\nCurrent File: %3") .arg(i).arg(size).arg(files[i])); qApp->processEvents(); if (progressDialog.wasCanceled()) break; if(!createServerFile( files[i],path,dir)) { k=1;//to stop back up of session logs incase of failure with certificate logs break; } } } if(QFile().error()==QFile::CopyError) QMessageBox::information(this,tr("DocmaQ Log Manager"),tr("Back Up failed due to an error.\n\nOperation Aborted !!"),QMessageBox::Ok); else { if(q==1) QMessageBox::information(this,tr("DocmaQ Log Manager"),tr("Back Up Successful !!"),QMessageBox::Ok); } }
ArkViewer::~ArkViewer() { if (m_part) { QProgressDialog progressDialog(this); progressDialog.setWindowTitle(i18n("Closing preview")); progressDialog.setLabelText(i18n("Please wait while the preview is being closed...")); progressDialog.setMinimumDuration(500); progressDialog.setModal(true); progressDialog.setCancelButton(nullptr); progressDialog.setRange(0, 0); // #261785: this preview dialog is not modal, so we need to delete // the previewed file ourselves when the dialog is closed; m_part.data()->closeUrl(); if (!m_fileName.isEmpty()) { QFile::remove(m_fileName); } } guiFactory()->removeClient(m_part); delete m_part; }
//--------------------------------------- QStringList FRDialog::findFiles(const QStringList &files, const QString &text) { QProgressDialog progressDialog(this); progressDialog.setCancelButtonText(tr("&Cancel")); progressDialog.setRange(0, files.size()); progressDialog.setWindowTitle(tr("Find Files")); QStringList foundFiles; for (int i = 0; i < files.size(); ++i) { progressDialog.setValue(i); progressDialog.setLabelText(tr("Searching file number %1 of %2...") .arg(i).arg(files.size())); qApp->processEvents(); if (progressDialog.wasCanceled()) break; QFile file(currentDir.absoluteFilePath(files[i])); if (file.open(QIODevice::ReadOnly)) { QString line; QTextStream in(&file); while (!in.atEnd()) { if (progressDialog.wasCanceled()) break; line = in.readLine(); if (line.contains(text)) { foundFiles << files[i]; break; } } } } foundFiles.removeOne(" ___Instruction"); foundFiles.removeOne(Config::configuration()->CurProject().split("/").last()); return foundFiles; }
void MainWindow::on_actionExport_to_PGN_triggered() { QFileDialog openFileDialog(this); openFileDialog.exec(); openFileDialog.setFilter("*.pgn"); if(openFileDialog.result() == QDialog::Accepted) { if(openFileDialog.selectedFiles().size() == 0) { return; } vector<int> ids; for(int i = 0; i < _gamesModel->rowCount(); ++i) { QModelIndex selectedElement = _gamesModel->index(i, 0); QString text = _gamesModel->data( _gamesModel->index(selectedElement.row(), 0)).toString(); ids.push_back(text.toInt()); } PGNExporter exporter; QProgressDialog progressDialog(QString("Import"), "", 0, 100); connect(&exporter, SIGNAL(onProgress(int)), &progressDialog, SLOT(setValue(int))); exporter.exportToFile(ids, openFileDialog.selectedFiles()[0]); // ui->pbClear->click(); } }
void MusicWidget::on_UpdateListButton_clicked() { QStringList files,filetype; QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8")); int num=0; filetype <<"*.mp3"<<"*.wav"; PlayList.removeAll("*"); QDir dir("/opt/qt-4.5/bin/"); QFileInfo tempFileInfo; QProgressDialog progressDialog(this); progressDialog.setWindowModality(Qt::WindowModal); progressDialog.setMinimumDuration(10); QFileInfoList list=dir.entryInfoList(filetype,QDir::Files); progressDialog.setCancelButtonText(tr("&取消")); progressDialog.setRange(0, list.size()); progressDialog.setWindowTitle(tr("更新播放列表")); for (int i = 0; i < list.size(); ++i) { progressDialog.setValue(i); tempFileInfo=list.at(i); num ++; files<<"/opt/qt-4.5/bin/"+tempFileInfo.fileName();//Add "mp3" and "wav" files to PlayList progressDialog.setLabelText(tr("找到 %1 of %2...").arg(num).arg(list.size())); if(progressDialog.wasCanceled()) return ; } PlayList = files; CurrentSong<<PlayList; UpdateListButton->setIcon(QPixmap("image/Update_2.png")); UpdateListButton->setIconSize(QPixmap("image/Update_2.png").size()); UpdateListButton->setAutoRaise(TRUE); MusicTitleLabe->setText(tr("更新完成")); }
void qAnimationDlg::preview() { //we'll take the rendering time into account! QElapsedTimer timer; timer.start(); setEnabled(false); //reset the interpolators and count the total number of frames int frameCount = countFrameAndResetInterpolators(); //show progress dialog QProgressDialog progressDialog(QString("Frames: %1").arg(frameCount), "Cancel", 0, frameCount, this); progressDialog.setWindowTitle("Preview"); progressDialog.show(); QApplication::processEvents(); double fps = fpsSpinBox->value(); int frameIndex = 0; for ( size_t i=0; i<m_videoSteps.size(); ++i ) { VideoStepItem& currentVideoStep = m_videoSteps[i]; //theoretical waiting time per frame qint64 delay_ms = static_cast<int>(1000 * currentVideoStep.duration_sec / fps); cc2DViewportObject currentParams; while ( currentVideoStep.interpolator.nextView( currentParams ) ) { timer.restart(); applyViewport ( ¤tParams ); qint64 dt_ms = timer.elapsed(); progressDialog.setValue(++frameIndex); QApplication::processEvents(); if (progressDialog.wasCanceled()) { break; } //remaining time if (dt_ms < delay_ms) { int wait_ms = static_cast<int>(delay_ms - dt_ms); #if defined(CC_WINDOWS) ::Sleep( wait_ms ); #else usleep( wait_ms * 1000 ); #endif } } } //reset view onCurrentStepChanged( getCurrentStepIndex() ); setEnabled(true); }
//-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- void ProgressInfoStatic::finished() { if (!isUpdatePossible()) return; assert(maxProgressStack().size() && progressStack().size() && progressSpanStack().size() && titleStack().size() && descriptionStack().size()); // Set progress to max value, and leave it there until somebody touches the progress again ProgressInfoStatic::setProgress(maxProgressStack().back()); // Pop all the stacks maxProgressStack().pop_back(); progressStack().pop_back(); progressSpanStack().pop_back(); titleStack().pop_back(); descriptionStack().pop_back(); // Update the text to reflect the "previous level" progressDialog()->setLabelText(currentComposedLabel()); // If we are finishing the last level, clean up if (!maxProgressStack().size()) { if (progressDialog() != NULL) { progressDialog()->hide(); delete progressDialog(); } } // Make sure the Gui is repainted //QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents); if (progressDialog()) progressDialog()->repaint(); }
bool AndroidExporter::ExportWholeProject(gd::Project& project, gd::String exportDir) { gd::Project exportedProject = project; #if !defined(GD_NO_WX_GUI) wxProgressDialog progressDialog(_("Export in progress"), _("Exporting the project...")); #endif // Prepare export directory gd::String assetsDir = exportDir + "/assets"; fs.MkDir(exportDir); fs.MkDir(assetsDir); fs.CopyDir(GetAndroidProjectPath(), exportDir); fs.CopyDir(GetSourcesPath() + "/GDCpp", exportDir + "/jni/GDCpp"); fs.CopyDir(GetSourcesPath() + "/Core", exportDir + "/jni/Core"); fs.CopyDir(GetSourcesPath() + "/Extensions", exportDir + "/jni/Extensions"); // Export the resources (before generating events as some resources filenames // may be updated) #if !defined(GD_NO_WX_GUI) ExportResources(fs, exportedProject, assetsDir, &progressDialog); #else ExportResources(fs, exportedProject, assetsDir, NULL); #endif // Generate events code if (!ExportEventsCode(exportedProject, exportDir)) return false; // Export source files /*if ( !ExportExternalSourceFiles(exportedProject, fs.GetTempDir()+"/GDTemporaries/JSCodeTemp/", includesFiles) ) { gd::LogError(_("Error during exporting! Unable to export source files:\n")+lastError); return false; }*/ ExportMainFile(exportedProject, exportDir); // Strip the project (*after* generating events as the events may use stripped // things (objects groups...)) gd::ProjectStripper::StripProjectForExport(exportedProject); // Export the project file gd::SerializerElement rootElement; exportedProject.SerializeTo(rootElement); if (!fs.WriteToFile(exportDir + "/assets/gd-project.json", gd::Serializer::ToJSON(rootElement))) return false; return true; }
void Player::addDirToLibrary() { QString dir = QFileDialog::getExistingDirectory(this, tr("Select music directory")); if (dir.isEmpty()) return; ProgressDialog progressDialog(this); connect(DataBase::instance(), SIGNAL(dirAddProgress(int,int)), &progressDialog, SLOT(setValue(int,int))); progressDialog.adjustSize(); progressDialog.show(); DataBase::instance()->addDirectory(dir); progressDialog.close(); }
QStringList Window::findFiles(const QStringList &files, const QString &text) { QProgressDialog progressDialog(this); progressDialog.setCancelButtonText("&Cancel"); progressDialog.setRange(0, files.size()); progressDialog.setWindowTitle("Find Files"); QStringList foundFiles; for (int i=0; i<files.size(); ++i) { progressDialog.setValue(i); progressDialog.setLabelText(tr("Searching file number %1 of %2...") .arg(i) .arg(files.size()) ); qApp->processEvents(); if (progressDialog.wasCanceled()) { break; } QFile file(currentDir.absoluteFilePath(files[i])); if (file.open(QIODevice::ReadOnly)) { QString line; QTextStream in(&file); while (in.atEnd() != true) { if (progressDialog.wasCanceled()) { break; } line = in.readLine(); if (line.contains(text)) { foundFiles << files[i]; break; } } } } return foundFiles; }
//-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- void ProgressInfoStatic::setProgress(size_t progressValue) { if (!isUpdatePossible()) return; if (progressValue == progressStack().back()) return; // Do nothing if no progress. // Guard against the max value set for this level if (progressValue > maxProgressStack().back()) progressValue = maxProgressStack().back(); progressStack().back() = progressValue; progressSpanStack().back() = 1; int totalProgress = static_cast<int>(currentTotalProgress()); int totalMaxProgress = static_cast<int>(currentTotalMaxProgressValue()); assert(static_cast<int>(totalProgress) <= totalMaxProgress); progressDialog()->setMaximum(totalMaxProgress); progressDialog()->setValue(totalProgress); //QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents); if (progressDialog()) progressDialog()->repaint(); }
void MainWindow::downloadFiles(const QString & path, const QVector<mtp::ObjectId> &objects) { qDebug() << "downloading to " << path; ProgressDialog progressDialog(this); progressDialog.show(); connect(_uploader, SIGNAL(uploadProgress(float)), &progressDialog, SLOT(setValue(float))); connect(_uploader, SIGNAL(uploadSpeed(qint64)), &progressDialog, SLOT(setSpeed(qint64))); connect(_uploader, SIGNAL(uploadStarted(QString)), &progressDialog, SLOT(setFilename(QString))); connect(_uploader, SIGNAL(finished()), &progressDialog, SLOT(accept())); connect(&progressDialog, SIGNAL(abort()), _uploader, SLOT(abort())); _uploader->download(path, objects); progressDialog.exec(); }
void NetfondsHistoryDownload::download(QStringList symbols) { _stop = FALSE; QNetworkAccessManager manager; QEventLoop eventLoop; QProgressDialog progressDialog("Downloading...", "Cancel", 0, symbols.size()); connect(&progressDialog, SIGNAL(canceled()), this, SLOT(stop())); connect(&progressDialog, SIGNAL(canceled()), &eventLoop, SLOT(quit())); progressDialog.setWindowModality(Qt::ApplicationModal); progressDialog.show(); for (int loop = 0; (!_stop && loop < symbols.size()); loop++) { progressDialog.setValue(loop); QString symbol = symbols.at(loop); symbol = symbol.trimmed(); if (symbol.isEmpty()) continue; QString name; name = symbol; // get the url QString url; getUrl(symbol, url); QStringList mess; mess << url; mess << tr("Downloading") << symbol; emit signalMessage(mess.join(" ")); mess << "..."; progressDialog.setLabelText(QString("Downloading ").append(symbol).append("...")); // download the data QNetworkReply *reply = manager.get(QNetworkRequest(QUrl(url))); connect(&progressDialog, SIGNAL(canceled()), &eventLoop, SLOT(quit())); QObject::connect(&manager, SIGNAL(finished(QNetworkReply *)), &eventLoop, SLOT(quit())); eventLoop.exec(); // parse the data and save quotes QByteArray ba = reply->readAll(); parseHistory(ba, symbol, name); } }
//! [5] QStringList Window::findFiles(const QStringList &files, const QString &text) { QProgressDialog progressDialog(this); progressDialog.setCancelButtonText(tr("&Cancel")); progressDialog.setRange(0, files.size()); progressDialog.setWindowTitle(tr("Find Files")); //! [5] //! [6] QMimeDatabase mimeDatabase; QStringList foundFiles; for (int i = 0; i < files.size(); ++i) { progressDialog.setValue(i); progressDialog.setLabelText( tr("Searching file number %1 of %n...", 0, files.size()).arg(i)); QCoreApplication::processEvents(); //! [6] if (progressDialog.wasCanceled()) break; //! [7] const QString fileName = files.at(i); const QMimeType mimeType = mimeDatabase.mimeTypeForFile(fileName); if (mimeType.isValid() && !mimeType.inherits(QStringLiteral("text/plain"))) { qWarning() << "Not searching binary file " << QDir::toNativeSeparators(fileName); continue; } QFile file(fileName); if (file.open(QIODevice::ReadOnly)) { QString line; QTextStream in(&file); while (!in.atEnd()) { if (progressDialog.wasCanceled()) break; line = in.readLine(); if (line.contains(text, Qt::CaseInsensitive)) { foundFiles << files[i]; break; } } } } return foundFiles; }
void PluginDialog::on_button_downloadFromURL_clicked() { bool ok; QString URL = QInputDialog::getText(this, tr("Download from URL"), tr("URL to zip file:"), QLineEdit::Normal, "", &ok); if(ok && !URL.isEmpty()) { QProgressDialog progressDialog(tr("Installing plugin from URL..."), tr("Cancel"), 0, 4, this); progressDialog.setWindowModality(Qt::WindowModal); progressDialog.setAutoReset(true); progressDialog.setAutoClose(true); connect(pluginManager, SIGNAL(installationProgress(int)), &progressDialog, SLOT(setValue(int))); connect(pluginManager, SIGNAL(installationError(QString)), &progressDialog, SLOT(close())); connect(pluginManager, SIGNAL(installationError(QString)), this, SLOT(pluginInstallError(QString))); connect(&progressDialog, SIGNAL(canceled()), this, SLOT(cancelInstallation())); progressDialog.show(); QStringList toInstall; toInstall << URL; pluginManager->installPlugins(toInstall); while(progressDialog.isVisible()) { qApp->processEvents(QEventLoop::WaitForMoreEvents); } }
void MainWindow::on_actionImport_PGN_triggered() { QFileDialog openFileDialog(this); openFileDialog.exec(); openFileDialog.setFilter("*.pgn"); if(openFileDialog.result() == QDialog::Accepted) { if(openFileDialog.selectedFiles().size() == 0) { return; } PGNImporter importer; QProgressDialog progressDialog(QString("Import"), "", 0, 100); connect(&importer, SIGNAL(onProgress(int)), &progressDialog, SLOT(setValue(int))); importer.importFromFile(openFileDialog.selectedFiles()[0]); ui->pbClear->click(); } }
void MainWindow::uploadFiles(const QStringList &files) { if (files.isEmpty()) return; qDebug() << "uploadFiles " << files; _uploadAnswer = 0; _proxyModel->setSourceModel(NULL); ProgressDialog progressDialog(this); progressDialog.setModal(true); progressDialog.setValue(0); connect(_uploader, SIGNAL(uploadProgress(float)), &progressDialog, SLOT(setValue(float))); connect(_uploader, SIGNAL(uploadSpeed(qint64)), &progressDialog, SLOT(setSpeed(qint64))); connect(_uploader, SIGNAL(uploadStarted(QString)), &progressDialog, SLOT(setFilename(QString))); connect(_uploader, SIGNAL(finished()), &progressDialog, SLOT(accept())); connect(&progressDialog, SIGNAL(abort()), _uploader, SLOT(abort())); _uploader->upload(files); progressDialog.exec(); _objectModel->moveToThread(QApplication::instance()->thread()); _proxyModel->setSourceModel(_objectModel); }
void QgsGPSPlugin::importGPSFile( const QString& inputFileName, QgsBabelFormat* importer, bool importWaypoints, bool importRoutes, bool importTracks, const QString& outputFileName, const QString& layerName ) { // what features does the user want to import? QString typeArg; if ( importWaypoints ) typeArg = QStringLiteral( "-w" ); else if ( importRoutes ) typeArg = QStringLiteral( "-r" ); else if ( importTracks ) typeArg = QStringLiteral( "-t" ); // try to start the gpsbabel process QStringList babelArgs = importer->importCommand( mBabelPath, typeArg, inputFileName, outputFileName ); QgsDebugMsg( QString( "Import command: " ) + babelArgs.join( "|" ) ); QProcess babelProcess; babelProcess.start( babelArgs.join( QStringLiteral( " " ) ) ); if ( !babelProcess.waitForStarted() ) { QMessageBox::warning( nullptr, tr( "Could not start process" ), tr( "Could not start GPSBabel!" ) ); return; } // wait for gpsbabel to finish (or the user to cancel) QProgressDialog progressDialog( tr( "Importing data..." ), tr( "Cancel" ), 0, 0 ); progressDialog.setWindowModality( Qt::WindowModal ); for ( int i = 0; babelProcess.state() == QProcess::Running; ++i ) { progressDialog.setValue( i / 64 ); if ( progressDialog.wasCanceled() ) return; } babelProcess.waitForFinished(); // did we get any data? if ( babelProcess.exitCode() != 0 ) { QString babelError( babelProcess.readAllStandardError() ); QString errorMsg( tr( "Could not import data from %1!\n\n" ) .arg( inputFileName ) ); errorMsg += babelError; QMessageBox::warning( nullptr, tr( "Error importing data" ), errorMsg ); return; } // add the layer if ( importTracks ) emit drawVectorLayer( outputFileName + "?type=track", layerName, QStringLiteral( "gpx" ) ); if ( importRoutes ) emit drawVectorLayer( outputFileName + "?type=route", layerName, QStringLiteral( "gpx" ) ); if ( importWaypoints ) emit drawVectorLayer( outputFileName + "?type=waypoint", layerName, QStringLiteral( "gpx" ) ); emit closeGui(); }
bool FlpImport::tryFLPImport( trackContainer * _tc ) { const int mappedFilter[] = { basicFilters<>::LowPass,// fast LP basicFilters<>::LowPass, basicFilters<>::BandPass_CSG, basicFilters<>::HiPass, basicFilters<>::Notch, basicFilters<>::NumFilters+basicFilters<>::LowPass, basicFilters<>::LowPass, basicFilters<>::NumFilters+basicFilters<>::LowPass } ; const Arpeggiator::ArpDirections mappedArpDir[] = { Arpeggiator::ArpDirUp, Arpeggiator::ArpDirUp, Arpeggiator::ArpDirDown, Arpeggiator::ArpDirUpAndDown, Arpeggiator::ArpDirUpAndDown, Arpeggiator::ArpDirRandom } ; QMap<QString, int> mappedPluginTypes; // instruments mappedPluginTypes["sampler"] = FL_Plugin::Sampler; mappedPluginTypes["ts404"] = FL_Plugin::TS404; mappedPluginTypes["3x osc"] = FL_Plugin::Fruity_3x_Osc; mappedPluginTypes["beepmap"] = FL_Plugin::BeepMap; mappedPluginTypes["buzz generator adapter"] = FL_Plugin::BuzzGeneratorAdapter; mappedPluginTypes["fruit kick"] = FL_Plugin::FruitKick; mappedPluginTypes["fruity drumsynth live"] = FL_Plugin::FruityDrumSynthLive; mappedPluginTypes["fruity dx10"] = FL_Plugin::FruityDX10; mappedPluginTypes["fruity granulizer"] = FL_Plugin::FruityGranulizer; mappedPluginTypes["fruity slicer"] = FL_Plugin::FruitySlicer; mappedPluginTypes["fruity soundfont player"] = FL_Plugin::FruitySoundfontPlayer; mappedPluginTypes["fruity vibrator"] = FL_Plugin::FruityVibrator; mappedPluginTypes["midi out"] = FL_Plugin::MidiOut; mappedPluginTypes["plucked!"] = FL_Plugin::Plucked; mappedPluginTypes["simsynth"] = FL_Plugin::SimSynth; mappedPluginTypes["sytrus"] = FL_Plugin::Sytrus; mappedPluginTypes["wasp"] = FL_Plugin::WASP; // effects mappedPluginTypes["fruity 7 band EQ"] = FL_Plugin::Fruity7BandEq; mappedPluginTypes["fruity balance"] = FL_Plugin::FruityBalance; mappedPluginTypes["fruity bass boost"] = FL_Plugin::FruityBassBoost; mappedPluginTypes["fruity big clock"] = FL_Plugin::FruityBigClock; mappedPluginTypes["fruity blood overdrive"] = FL_Plugin::FruityBloodOverdrive; mappedPluginTypes["fruity center"] = FL_Plugin::FruityCenter; mappedPluginTypes["fruity chorus"] = FL_Plugin::FruityChorus; mappedPluginTypes["fruity compressor"] = FL_Plugin::FruityCompressor; mappedPluginTypes["fruity db meter"] = FL_Plugin::FruityDbMeter; mappedPluginTypes["fruity delay"] = FL_Plugin::FruityDelay; mappedPluginTypes["fruity delay 2"] = FL_Plugin::FruityDelay2; mappedPluginTypes["fruity fast dist"] = FL_Plugin::FruityFastDist; mappedPluginTypes["fruity fast lp"] = FL_Plugin::FruityFastLP; mappedPluginTypes["fruity filter"] = FL_Plugin::FruityFilter; mappedPluginTypes["fruity flanger"] = FL_Plugin::FruityFlanger; mappedPluginTypes["fruity formula controller"] = FL_Plugin::FruityFormulaController; mappedPluginTypes["fruity free filter"] = FL_Plugin::FruityFreeFilter; mappedPluginTypes["fruity html notebook"] = FL_Plugin::FruityHTMLNotebook; mappedPluginTypes["fruity lsd"] = FL_Plugin::FruityLSD; mappedPluginTypes["fruity mute 2"] = FL_Plugin::FruityMute2; mappedPluginTypes["fruity notebook"] = FL_Plugin::FruityNotebook; mappedPluginTypes["fruity panomatic"] = FL_Plugin::FruityPanOMatic; mappedPluginTypes["fruity parametric eq"] = FL_Plugin::FruityParametricEQ; mappedPluginTypes["fruity peak controller"] = FL_Plugin::FruityPeakController; mappedPluginTypes["fruity phase inverter"] = FL_Plugin::FruityPhaseInverter; mappedPluginTypes["fruity phaser"] = FL_Plugin::FruityPhaser; mappedPluginTypes["fruity reeverb"] = FL_Plugin::FruityReeverb; mappedPluginTypes["fruity scratcher"] = FL_Plugin::FruityScratcher; mappedPluginTypes["fruity send"] = FL_Plugin::FruitySend; mappedPluginTypes["fruity soft clipper"] = FL_Plugin::FruitySoftClipper; mappedPluginTypes["fruity spectroman"] = FL_Plugin::FruitySpectroman; mappedPluginTypes["fruity stereo enhancer"] = FL_Plugin::FruityStereoEnhancer; mappedPluginTypes["fruity x-y controller"] = FL_Plugin::FruityXYController; FL_Project p; if( openFile() == false ) { return false; } if( readID() != makeID( 'F', 'L', 'h', 'd' ) ) { qWarning( "FlpImport::tryImport(): not a valid FL project\n" ); return false; } const int header_len = read32LE(); if( header_len != 6 ) { qWarning( "FlpImport::tryImport(): invalid file format\n" ); return false; } const int type = read16LE(); if( type != 0 ) { qWarning( "FlpImport::tryImport(): type %d format is not " "supported\n", type ); return false; } p.numChannels = read16LE(); if( p.numChannels < 1 || p.numChannels > 1000 ) { qWarning( "FlpImport::tryImport(): invalid number of channels " "(%d)\n", p.numChannels ); return false; } const int ppq = read16LE(); if( ppq < 0 ) { qWarning( "FlpImport::tryImport(): invalid ppq\n" ); return false; } QProgressDialog progressDialog( trackContainer::tr( "Importing FLP-file..." ), trackContainer::tr( "Cancel" ), 0, p.numChannels ); progressDialog.setWindowTitle( trackContainer::tr( "Please wait..." ) ); progressDialog.show(); bool valid = false; // search for FLdt chunk while( 1 ) { Sint32 id = readID(); const int len = read32LE(); if( file().atEnd() ) { qWarning( "FlpImport::tryImport(): unexpected " "end of file\n" ); return false; } if( len < 0 || len >= 0x10000000 ) { qWarning( "FlpImport::tryImport(): invalid " "chunk length %d\n", len ); return false; } if( id == makeID( 'F', 'L', 'd', 't' ) ) { valid = true; break; } skip( len ); } if( valid == false ) { return false; } for( int i = 0; i < p.numChannels; ++i ) { p.channels += FL_Channel(); } qDebug( "channels: %d\n", p.numChannels ); char * text = NULL; int text_len = 0; FL_Plugin::PluginTypes last_plugin_type = FL_Plugin::UnknownPlugin; int cur_channel = -1; const bool is_journ = engine::projectJournal()->isJournalling(); engine::projectJournal()->setJournalling( false ); while( file().atEnd() == false ) { FLP_Events ev = static_cast<FLP_Events>( readByte() ); Uint32 data = readByte(); if( ev >= FLP_Word && ev < FLP_Text ) { data = data | ( readByte() << 8 ); } if( ev >= FLP_Int && ev < FLP_Text ) { data = data | ( readByte() << 16 ); data = data | ( readByte() << 24 ); } if( ev >= FLP_Text ) { text_len = data & 0x7F; Uint8 shift = 0; while( data & 0x80 ) { data = readByte(); text_len = text_len | ( ( data & 0x7F ) << ( shift += 7 ) ); } delete[] text; text = new char[text_len+1]; if( readBlock( text, text_len ) <= 0 ) { qWarning( "could not read string (len: %d)\n", text_len ); } text[text_len] = 0; } const unsigned char * puc = (const unsigned char*) text; const int * pi = (const int *) text; FL_Channel * cc = cur_channel >= 0 ? &p.channels[cur_channel] : NULL; switch( ev ) { // BYTE EVENTS case FLP_Byte: qDebug( "undefined byte %d\n", data ); break; case FLP_NoteOn: qDebug( "note on: %d\n", data ); // data = pos how to handle? break; case FLP_Vol: qDebug( "vol %d\n", data ); break; case FLP_Pan: qDebug( "pan %d\n", data ); break; case FLP_LoopActive: qDebug( "active loop: %d\n", data ); break; case FLP_ShowInfo: qDebug( "show info: %d\n", data ); break; case FLP_Shuffle: qDebug( "shuffle: %d\n", data ); break; case FLP_MainVol: p.mainVolume = data * 100 / 128; break; case FLP_PatLength: qDebug( "pattern length: %d\n", data ); break; case FLP_BlockLength: qDebug( "block length: %d\n", data ); break; case FLP_UseLoopPoints: cc->sampleUseLoopPoints = true; break; case FLP_LoopType: qDebug( "loop type: %d\n", data ); break; case FLP_ChanType: qDebug( "channel type: %d\n", data ); if( cc ) { switch( data ) { case 0: cc->pluginType = FL_Plugin::Sampler; break; case 1: cc->pluginType = FL_Plugin::TS404; break; // case 2: cc->pluginType = FL_Plugin::Fruity_3x_Osc; break; case 3: cc->pluginType = FL_Plugin::Layer; break; default: break; } } break; case FLP_MixSliceNum: cc->fxChannel = data+1; break; case FLP_EffectChannelMuted: if( p.currentEffectChannel <= NumFLFxChannels ) { p.effectChannels[p.currentEffectChannel].isMuted = ( data & 0x08 ) > 0 ? false : true; } break; // WORD EVENTS case FLP_NewChan: cur_channel = data; qDebug( "new channel: %d\n", data ); break; case FLP_NewPat: p.currentPattern = data - 1; if( p.currentPattern > p.maxPatterns ) { p.maxPatterns = p.currentPattern; } break; case FLP_Tempo: p.tempo = data; break; case FLP_CurrentPatNum: p.activeEditPattern = data; break; case FLP_FX: qDebug( "FX: %d\n", data ); break; case FLP_Fade_Stereo: if( data & 0x02 ) { cc->sampleReversed = true; } else if( data & 0x100 ) { cc->sampleReverseStereo = true; } qDebug( "fade stereo: %d\n", data ); break; case FLP_CutOff: qDebug( "cutoff (sample): %d\n", data ); break; case FLP_PreAmp: cc->sampleAmp = 100 + data * 100 / 256; break; case FLP_Decay: qDebug( "decay (sample): %d\n", data ); break; case FLP_Attack: qDebug( "attack (sample): %d\n", data ); break; case FLP_MainPitch: p.mainPitch = data; break; case FLP_Resonance: qDebug( "reso (sample): %d\n", data ); break; case FLP_LoopBar: qDebug( "loop bar: %d\n", data ); break; case FLP_StDel: qDebug( "stdel (delay?): %d\n", data ); break; case FLP_FX3: qDebug( "FX 3: %d\n", data ); break; case FLP_ShiftDelay: qDebug( "shift delay: %d\n", data ); break; case FLP_Dot: cc->dots.push_back( ( data & 0xff ) + ( p.currentPattern << 8 ) ); break; case FLP_LayerChans: p.channels[data].layerParent = cur_channel; // DWORD EVENTS case FLP_Color: cc->color = data; break; case FLP_PlayListItem: { FL_PlayListItem i; i.position = ( data & 0xffff ) * DefaultTicksPerTact; i.length = DefaultTicksPerTact; i.pattern = ( data >> 16 ) - 1; p.playListItems.push_back( i ); if( i.pattern > p.maxPatterns ) { p.maxPatterns = i.pattern; } break; } case FLP_FXSine: qDebug( "fx sine: %d\n", data ); break; case FLP_CutCutBy: qDebug( "cut cut by: %d\n", data ); break; case FLP_MiddleNote: cc->baseNote = data+9; break; case FLP_DelayReso: qDebug( "delay resonance: %d\n", data ); break; case FLP_Reverb: qDebug( "reverb (sample): %d\n", data ); break; case FLP_IntStretch: qDebug( "int stretch (sample): %d\n", data ); break; // TEXT EVENTS case FLP_Text_ChanName: cc->name = text; break; case FLP_Text_PatName: p.patternNames[p.currentPattern] = text; break; case FLP_Text_CommentRTF: { QByteArray ba( text, text_len ); QBuffer buf( &ba ); buf.open( QBuffer::ReadOnly ); lineno = 0; attr_clear_all(); op = html_init(); hash_init(); Word * word = word_read( &buf ); QString out; word_print( word, out ); word_free( word ); op_free( op ); p.projectNotes = out; outstring = ""; break; } case FLP_Text_Title: p.projectTitle = text; break; case FLP_Text_SampleFileName: { QString f = ""; QString f_name = text; /* if( f.mid( 1, 11 ) == "Instruments" ) { f = "\\Patches\\Packs" + f.mid( 12 ); }*/ bool foundFile = false; f_name.replace( '\\', QDir::separator() ); if( QFileInfo( configManager::inst()->flDir() + "/Data/" ).exists() ) { f = configManager::inst()->flDir() + "/Data/" + f_name; foundFile = QFileInfo( f ).exists(); } else { // FL 3 compat f = configManager::inst()->flDir() + "/Samples/" + f_name; foundFile = QFileInfo( f ).exists(); } if( ! foundFile ) { // look in same directory as .flp file f = m_fileBase + "/" + QFileInfo( f_name ).fileName(); printf("looking in %s for samples\n", qPrintable(f)); foundFile = QFileInfo( f ).exists(); } cc->sampleFileName = f; break; } case FLP_Text_Version: { qDebug( "FLP version: %s\n", text ); p.versionString = text; QStringList l = p.versionString.split( '.' ); p.version = ( l[0].toInt() << 8 ) + ( l[1].toInt() << 4 ) + ( l[2].toInt() << 0 ); if( p.version >= 0x600 ) { p.versionSpecificFactor = 100; } break; } case FLP_Text_PluginName: if( mappedPluginTypes. contains( QString( text ).toLower() ) ) { const FL_Plugin::PluginTypes t = static_cast<FL_Plugin::PluginTypes>( mappedPluginTypes[QString( text ).toLower()] ); if( t > FL_Plugin::EffectPlugin ) { qDebug( "recognized new effect %s\n", text ); p.effects.push_back( FL_Effect( t ) ); } else if( cc ) { qDebug( "recognized new plugin %s\n", text ); cc->pluginType = t; } last_plugin_type = t; } else { qDebug( "unsupported plugin: %s!\n", text ); } break; case FLP_Text_EffectChanName: ++p.currentEffectChannel; if( p.currentEffectChannel <= NumFLFxChannels ) { p.effectChannels[p.currentEffectChannel].name = text; } break; case FLP_Text_Delay: qDebug( "delay data: " ); // pi[1] seems to be volume or similiar and // needs to be divided // by p.versionSpecificFactor dump_mem( text, text_len ); break; case FLP_Text_TS404Params: if( cc && cc->pluginType == FL_Plugin::UnknownPlugin && cc->pluginSettings == NULL ) { cc->pluginSettings = new char[text_len]; memcpy( cc->pluginSettings, text, text_len ); cc->pluginSettingsLength = text_len; cc->pluginType = FL_Plugin::TS404; } break; case FLP_Text_NewPlugin: if( last_plugin_type > FL_Plugin::EffectPlugin ) { FL_Effect * e = &p.effects.last(); e->fxChannel = puc[0]; e->fxPos = puc[4]; qDebug( "new effect: " ); } else { qDebug( "new plugin: " ); } dump_mem( text, text_len ); break; case FLP_Text_PluginParams: if( cc && cc->pluginSettings == NULL ) { cc->pluginSettings = new char[text_len]; memcpy( cc->pluginSettings, text, text_len ); cc->pluginSettingsLength = text_len; } qDebug( "plugin params: " ); dump_mem( text, text_len ); break; case FLP_Text_ChanParams: cc->arpDir = mappedArpDir[pi[10]]; cc->arpRange = pi[11]; cc->selectedArp = pi[12]; if( cc->selectedArp < 8 ) { const int mappedArps[] = { 0, 1, 5, 6, 2, 3, 4 } ; cc->selectedArp = mappedArps[cc->selectedArp]; } cc->arpTime = ( ( pi[13]+1 ) * p.tempo ) / ( 4*16 ) + 1; cc->arpGate = ( pi[14] * 100.0f ) / 48.0f; cc->arpEnabled = pi[10] > 0; qDebug( "channel params: " ); dump_mem( text, text_len ); break; case FLP_Text_EnvLfoParams: { const float scaling = 1.0 / 65536.0f; FL_Channel_Envelope e; switch( cc->envelopes.size() ) { case 1: e.target = InstrumentSoundShaping::Volume; break; case 2: e.target = InstrumentSoundShaping::Cut; break; case 3: e.target = InstrumentSoundShaping::Resonance; break; default: e.target = InstrumentSoundShaping::NumTargets; break; } e.predelay = pi[2] * scaling; e.attack = pi[3] * scaling; e.hold = pi[4] * scaling; e.decay = pi[5] * scaling; e.sustain = 1-pi[6] / 128.0f; e.release = pi[7] * scaling; if( e.target == InstrumentSoundShaping::Volume ) { e.amount = pi[1] ? 1 : 0; } else { e.amount = pi[8] / 128.0f; } // e.lfoAmount = pi[11] / 128.0f; cc->envelopes.push_back( e ); qDebug( "envelope and lfo params:\n" ); dump_mem( text, text_len ); break; } case FLP_Text_BasicChanParams: cc->volume = ( pi[1] / p.versionSpecificFactor ) * 100 / 128; cc->panning = ( pi[0] / p.versionSpecificFactor ) * 200 / 128 - PanningRight; if( text_len > 12 ) { cc->filterType = mappedFilter[puc[20]]; cc->filterCut = puc[12] / ( 255.0f * 2.5f ); cc->filterRes = 0.01f + puc[16] / ( 256.0f * 2 ); cc->filterEnabled = ( puc[13] == 0 ); if( puc[20] >= 6 ) { cc->filterCut *= 0.5f; } } qDebug( "basic chan params: " ); dump_mem( text, text_len ); break; case FLP_Text_OldFilterParams: cc->filterType = mappedFilter[puc[8]]; cc->filterCut = puc[0] / ( 255.0f * 2.5 ); cc->filterRes = 0.1f + puc[4] / ( 256.0f * 2 ); cc->filterEnabled = ( puc[1] == 0 ); if( puc[8] >= 6 ) { cc->filterCut *= 0.5; } qDebug( "old filter params: " ); dump_mem( text, text_len ); break; case FLP_Text_AutomationData: { const int bpae = 12; const int imax = text_len / bpae; qDebug( "automation data (%d items)\n", imax ); for( int i = 0; i < imax; ++i ) { FL_Automation a; a.pos = pi[3*i+0] / ( 4*ppq / DefaultTicksPerTact ); a.value = pi[3*i+2]; a.channel = pi[3*i+1] >> 16; a.control = pi[3*i+1] & 0xffff; if( a.channel >= 0 && a.channel < p.numChannels ) { qDebug( "add channel %d at %d val %d control:%d\n", a.channel, a.pos, a.value, a.control ); p.channels[a.channel].automationData += a; } // dump_mem( text+i*bpae, bpae ); } break; } case FLP_Text_PatternNotes: { //dump_mem( text, text_len ); const int bpn = 20; const int imax = ( text_len + bpn - 1 ) / bpn; for( int i = 0; i < imax; ++i ) { int ch = *( puc + i*bpn + 6 ); int pan = *( puc + i*bpn + 16 ); int vol = *( puc + i*bpn + 17 ); int pos = *( (int *)( puc + i*bpn ) ); int key = *( puc + i*bpn + 12 ); int len = *( (int*)( puc + i*bpn + 8 ) ); pos /= (4*ppq) / DefaultTicksPerTact; len /= (4*ppq) / DefaultTicksPerTact; note n( len, pos, key, vol * 100 / 128, pan*200 / 128 - 100 ); if( ch < p.numChannels ) { p.channels[ch].notes.push_back( qMakePair( p.currentPattern, n ) ); } else { qDebug( "invalid " ); } qDebug( "note: " ); dump_mem( text+i*bpn, bpn ); } break; } case FLP_Text_ChanGroupName: qDebug( "channel group name: %s\n", text ); break; // case 216: pi[2] /= p.versionSpecificFactor // case 229: pi[1] /= p.versionSpecificFactor case 225: { enum FLP_EffectParams { EffectParamVolume = 0x1fc0 } ; const int bpi = 12; const int imax = text_len / bpi; for( int i = 0; i < imax; ++i ) { const int param = pi[i*3+1] & 0xffff; const int ch = ( pi[i*3+1] >> 22 ) & 0x7f; if( ch < 0 || ch > NumFLFxChannels ) { continue; } const int val = pi[i*3+2]; if( param == EffectParamVolume ) { p.effectChannels[ch].volume = ( val / p.versionSpecificFactor ) * 100 / 128; } else { qDebug( "FX-ch: %d param: %x value:%x\n", ch, param, val ); } } break; } case 233: // playlist items { const int bpi = 28; const int imax = text_len / bpi; for( int i = 0; i < imax; ++i ) { const int pos = pi[i*bpi/sizeof(int)+0] / ( (4*ppq) / DefaultTicksPerTact ); const int len = pi[i*bpi/sizeof(int)+2] / ( (4*ppq) / DefaultTicksPerTact ); const int pat = pi[i*bpi/sizeof(int)+3] & 0xfff; if( pat > 2146 && pat <= 2278 ) // whatever these magic numbers are for... { FL_PlayListItem i; i.position = pos; i.length = len; i.pattern = 2278 - pat; p.playListItems += i; } else { qDebug( "unknown playlist item: " ); dump_mem( text+i*bpi, bpi ); } } break; } default: if( ev >= FLP_Text ) { qDebug( "!! unhandled text (ev: %d, len: %d): ", ev, text_len ); dump_mem( text, text_len ); } else { qDebug( "!! handling of FLP-event %d not implemented yet " "(data=%d).\n", ev, data ); } break; } } // now create a project from FL_Project data structure engine::getSong()->clearProject(); // configure the mixer for( int i=0; i<NumFLFxChannels; ++i ) { engine::fxMixer()->createChannel(); } engine::fxMixerView()->refreshDisplay(); // set global parameters engine::getSong()->setMasterVolume( p.mainVolume ); engine::getSong()->setMasterPitch( p.mainPitch ); engine::getSong()->setTempo( p.tempo ); // set project notes engine::getProjectNotes()->setText( p.projectNotes ); progressDialog.setMaximum( p.maxPatterns + p.channels.size() + p.effects.size() ); int cur_progress = 0; // create BB tracks QList<bbTrack *> bb_tracks; QList<InstrumentTrack *> i_tracks; while( engine::getBBTrackContainer()->numOfBBs() <= p.maxPatterns ) { const int cur_pat = bb_tracks.size(); bbTrack * bbt = dynamic_cast<bbTrack *>( track::create( track::BBTrack, engine::getSong() ) ); if( p.patternNames.contains( cur_pat ) ) { bbt->setName( p.patternNames[cur_pat] ); } bb_tracks += bbt; progressDialog.setValue( ++cur_progress ); qApp->processEvents(); } // create instrument-track for each channel for( QList<FL_Channel>::Iterator it = p.channels.begin(); it != p.channels.end(); ++it ) { InstrumentTrack * t = dynamic_cast<InstrumentTrack *>( track::create( track::InstrumentTrack, engine::getBBTrackContainer() ) ); engine::getBBTrackContainer()->updateAfterTrackAdd(); i_tracks.push_back( t ); switch( it->pluginType ) { case FL_Plugin::Fruity_3x_Osc: it->instrumentPlugin = t->loadInstrument( "tripleoscillator" ); break; case FL_Plugin::Plucked: it->instrumentPlugin = t->loadInstrument( "vibedstrings" ); break; case FL_Plugin::FruitKick: it->instrumentPlugin = t->loadInstrument( "kicker" ); break; case FL_Plugin::TS404: it->instrumentPlugin = t->loadInstrument( "lb302" ); break; case FL_Plugin::FruitySoundfontPlayer: it->instrumentPlugin = t->loadInstrument( "sf2player" ); break; case FL_Plugin::Sampler: case FL_Plugin::UnknownPlugin: default: it->instrumentPlugin = t->loadInstrument( "audiofileprocessor" ); break; } processPluginParams( &( *it ) ); t->setName( it->name ); t->volumeModel()->setValue( it->volume ); t->panningModel()->setValue( it->panning ); t->baseNoteModel()->setValue( it->baseNote ); t->effectChannelModel()->setValue( it->fxChannel ); InstrumentSoundShaping * iss = &t->m_soundShaping; iss->m_filterModel.setValue( it->filterType ); iss->m_filterCutModel.setValue( it->filterCut * ( iss->m_filterCutModel.maxValue() - iss->m_filterCutModel.minValue() ) + iss->m_filterCutModel.minValue() ); iss->m_filterResModel.setValue( it->filterRes * ( iss->m_filterResModel.maxValue() - iss->m_filterResModel.minValue() ) + iss->m_filterResModel.minValue() ); iss->m_filterEnabledModel.setValue( it->filterEnabled ); for( QList<FL_Channel_Envelope>::iterator jt = it->envelopes.begin(); jt != it->envelopes.end(); ++jt ) { if( jt->target != InstrumentSoundShaping::NumTargets ) { EnvelopeAndLfoParameters * elp = iss->m_envLfoParameters[jt->target]; elp->m_predelayModel.setValue( jt->predelay ); elp->m_attackModel.setValue( jt->attack ); elp->m_holdModel.setValue( jt->hold ); elp->m_decayModel.setValue( jt->decay ); elp->m_sustainModel.setValue( jt->sustain ); elp->m_releaseModel.setValue( jt->release ); elp->m_amountModel.setValue( jt->amount ); elp->updateSampleVars(); } } Arpeggiator * arp = &t->m_arpeggiator; arp->m_arpDirectionModel.setValue( it->arpDir ); arp->m_arpRangeModel.setValue( it->arpRange ); arp->m_arpModel.setValue( it->selectedArp ); arp->m_arpTimeModel.setValue( it->arpTime ); arp->m_arpGateModel.setValue( it->arpGate ); arp->m_arpEnabledModel.setValue( it->arpEnabled ); // process all dots for( QList<int>::ConstIterator jt = it->dots.begin(); jt != it->dots.end(); ++jt ) { const int pat = *jt / 256; const int pos = *jt % 256; pattern * p = dynamic_cast<pattern *>( t->getTCO( pat ) ); if( p == NULL ) { continue; } p->setStep( pos, true ); } // TODO: use future layering feature if( it->layerParent >= 0 ) { it->notes += p.channels[it->layerParent].notes; } // process all notes for( FL_Channel::noteVector::ConstIterator jt = it->notes.begin(); jt != it->notes.end(); ++jt ) { const int pat = jt->first; if( pat > 100 ) { continue; } pattern * p = dynamic_cast<pattern *>( t->getTCO( pat ) ); if( p != NULL ) { p->addNote( jt->second, false ); } } // process automation data for( QList<FL_Automation>::ConstIterator jt = it->automationData.begin(); jt != it->automationData.end(); ++jt ) { AutomatableModel * m = NULL; float value = jt->value; bool scale = false; switch( jt->control ) { case FL_Automation::ControlVolume: m = t->volumeModel(); value *= ( 100.0f / 128.0f ) / p.versionSpecificFactor; break; case FL_Automation::ControlPanning: m = t->panningModel(); value = ( value / p.versionSpecificFactor ) *200/128 - PanningRight; break; case FL_Automation::ControlPitch: m = t->pitchModel(); break; case FL_Automation::ControlFXChannel: m = t->effectChannelModel(); value = value*200/128 - PanningRight; break; case FL_Automation::ControlFilterCut: scale = true; m = &t->m_soundShaping.m_filterCutModel; value /= ( 255 * 2.5f ); break; case FL_Automation::ControlFilterRes: scale = true; m = &t->m_soundShaping.m_filterResModel; value = 0.1f + value / ( 256.0f * 2 ); break; case FL_Automation::ControlFilterType: m = &t->m_soundShaping.m_filterModel; value = mappedFilter[jt->value]; break; default: qDebug( "handling automation data of " "control %d not implemented " "yet\n", jt->control ); break; } if( m ) { if( scale ) { value = m->minValue<float>() + value * ( m->maxValue<float>() - m->minValue<float>() ); } AutomationPattern * p = AutomationPattern::globalAutomationPattern( m ); p->putValue( jt->pos, value, false ); } } progressDialog.setValue( ++cur_progress ); qApp->processEvents(); } // process all effects EffectKeyList effKeys; Plugin::DescriptorList pluginDescs; Plugin::getDescriptorsOfAvailPlugins( pluginDescs ); for( Plugin::DescriptorList::ConstIterator it = pluginDescs.begin(); it != pluginDescs.end(); ++it ) { if( it->type != Plugin::Effect ) { continue; } if( it->subPluginFeatures ) { it->subPluginFeatures->listSubPluginKeys( &( *it ), effKeys ); } else { effKeys << EffectKey( &( *it ), it->name ); } } for( int fx_ch = 0; fx_ch <= NumFLFxChannels ; ++fx_ch ) { FxChannel * ch = engine::fxMixer()->effectChannel( fx_ch ); if( !ch ) { continue; } FL_EffectChannel * flch = &p.effectChannels[fx_ch]; if( !flch->name.isEmpty() ) { ch->m_name = flch->name; } ch->m_volumeModel.setValue( flch->volume / 100.0f ); ch->m_muteModel.setValue( flch->isMuted ); } for( QList<FL_Effect>::ConstIterator it = p.effects.begin(); it != p.effects.end(); ++it ) { QString effName; switch( it->pluginType ) { case FL_Plugin::Fruity7BandEq: effName = "C* Eq2x2"; break; case FL_Plugin::FruityBassBoost: effName = "BassBooster"; break; case FL_Plugin::FruityChorus: effName = "TAP Chorus"; break; case FL_Plugin::FruityCompressor: //effName = "C* Compress"; effName = "Fast Lookahead limiter"; break; case FL_Plugin::FruityDelay: case FL_Plugin::FruityDelay2: // effName = "Feedback Delay Line (Maximum Delay 5s)"; break; case FL_Plugin::FruityBloodOverdrive: case FL_Plugin::FruityFastDist: case FL_Plugin::FruitySoftClipper: effName = "C* Clip"; break; case FL_Plugin::FruityFastLP: effName = "Low Pass Filter"; break; case FL_Plugin::FruityPhaser: effName = "C* PhaserI"; break; case FL_Plugin::FruityReeverb: effName = "C* Plate2x2"; break; case FL_Plugin::FruitySpectroman: effName = "Spectrum Analyzer"; break; default: break; } if( effName.isEmpty() || it->fxChannel < 0 || it->fxChannel > NumFLFxChannels ) { continue; } EffectChain * ec = &engine::fxMixer()-> effectChannel( it->fxChannel )->m_fxChain; qDebug( "adding %s to %d\n", effName.toUtf8().constData(), it->fxChannel ); for( EffectKeyList::Iterator jt = effKeys.begin(); jt != effKeys.end(); ++jt ) { if( QString( jt->desc->displayName ).contains( effName ) || ( jt->desc->subPluginFeatures != NULL && jt->name.contains( effName ) ) ) { qDebug( "instantiate %s\n", jt->desc->name ); ::Effect * e = Effect::instantiate( jt->desc->name, ec, &( *jt ) ); ec->appendEffect( e ); ec->setEnabled( true ); break; } } progressDialog.setValue( ++cur_progress ); qApp->processEvents(); } // process all playlist-items for( QList<FL_PlayListItem>::ConstIterator it = p.playListItems.begin(); it != p.playListItems.end(); ++it ) { if( it->pattern > p.maxPatterns ) { continue; } trackContentObject * tco = bb_tracks[it->pattern]->createTCO( midiTime() ); tco->movePosition( it->position ); if( it->length != DefaultTicksPerTact ) { tco->changeLength( it->length ); } } // set current pattern if( p.activeEditPattern < engine::getBBTrackContainer()->numOfBBs() ) { engine::getBBTrackContainer()->setCurrentBB( p.activeEditPattern ); } // restore journalling settings engine::projectJournal()->setJournalling( is_journ ); return true; }
void TupScreen::render() { #ifdef K_DEBUG T_FUNCINFO; #endif TupScene *scene = k->project->scene(k->currentSceneIndex); if (!scene) { #ifdef K_DEBUG tError() << "TupScreen::render() - [ Fatal Error ] - Scene is NULL! -> index: " << k->currentSceneIndex; #endif return; } k->sounds.clear(); foreach (TupSoundLayer *layer, scene->soundLayers().values()) k->sounds << layer; TupAnimationRenderer renderer(k->project->bgColor()); renderer.setScene(scene, k->project->dimension()); QFont font = this->font(); font.setPointSize(8); QProgressDialog progressDialog(this, Qt::WindowStaysOnTopHint | Qt::FramelessWindowHint | Qt::Dialog); progressDialog.setFont(font); progressDialog.setLabelText(tr("Rendering...")); progressDialog.setCancelButton(0); progressDialog.setRange(1, renderer.totalPhotograms()); QDesktopWidget desktop; progressDialog.move((int) (desktop.screenGeometry().width() - progressDialog.width())/2, (int) (desktop.screenGeometry().height() - progressDialog.height())/2); progressDialog.show(); QList<QImage> photogramList; int i = 1; while (renderer.nextPhotogram()) { QImage renderized = QImage(k->project->dimension(), QImage::Format_RGB32); QPainter painter(&renderized); painter.setRenderHint(QPainter::Antialiasing); renderer.render(&painter); if (k->isScaled) { QImage resized = renderized.scaledToWidth(k->screenDimension.width(), Qt::SmoothTransformation); photogramList << resized; } else { photogramList << renderized; } progressDialog.setValue(i); i++; } k->photograms = photogramList; k->animationList.replace(k->currentSceneIndex, photogramList); k->renderControl.replace(k->currentSceneIndex, true); }
void CGameListCtrl::CompressSelection(bool _compress) { wxString dirHome; wxGetHomeDir(&dirHome); wxDirDialog browseDialog(this, _("Browse for output directory"), dirHome, wxDD_DEFAULT_STYLE | wxDD_DIR_MUST_EXIST); if (browseDialog.ShowModal() != wxID_OK) return; bool all_good = true; { wxProgressDialog progressDialog( _compress ? _("Compressing ISO") : _("Decompressing ISO"), _("Working..."), 1000, this, wxPD_APP_MODAL | wxPD_ELAPSED_TIME | wxPD_ESTIMATED_TIME | wxPD_REMAINING_TIME | wxPD_SMOOTH ); m_currentItem = 0; m_numberItem = GetSelectedItemCount(); for (u32 i=0; i < m_numberItem; i++) { const GameListItem *iso = GetSelectedISO(); if (!iso->IsCompressed() && _compress) { std::string FileName, FileExt; SplitPath(iso->GetFileName(), NULL, &FileName, &FileExt); m_currentFilename = FileName; FileName.append(".gcz"); std::string OutputFileName; BuildCompleteFilename(OutputFileName, (const char *)browseDialog.GetPath().mb_str(wxConvUTF8), FileName); if (wxFileExists(wxString::FromAscii(OutputFileName.c_str())) && wxMessageBox( wxString::Format(_("The file %s already exists.\nDo you wish to replace it?"), wxString(OutputFileName.c_str(), *wxConvCurrent).c_str()), _("Confirm File Overwrite"), wxYES_NO) == wxNO) continue; all_good &= DiscIO::CompressFileToBlob(iso->GetFileName().c_str(), OutputFileName.c_str(), (iso->GetPlatform() == GameListItem::WII_DISC) ? 1 : 0, 16384, &MultiCompressCB, &progressDialog); } else if (iso->IsCompressed() && !_compress) { std::string FileName, FileExt; SplitPath(iso->GetFileName(), NULL, &FileName, &FileExt); m_currentFilename = FileName; if (iso->GetPlatform() == GameListItem::WII_DISC) FileName.append(".iso"); else FileName.append(".gcm"); std::string OutputFileName; BuildCompleteFilename(OutputFileName, (const char *)browseDialog.GetPath().mb_str(wxConvUTF8), FileName); if (wxFileExists(wxString::FromAscii(OutputFileName.c_str())) && wxMessageBox( wxString::Format(_("The file %s already exists.\nDo you wish to replace it?"), wxString(OutputFileName.c_str(), *wxConvCurrent).c_str()), _("Confirm File Overwrite"), wxYES_NO) == wxNO) continue; all_good &= DiscIO::DecompressBlobToFile(iso->GetFileName().c_str(), OutputFileName.c_str(), &MultiCompressCB, &progressDialog); } m_currentItem++; } } if (!all_good) wxMessageBox(_("Dolphin was unable to complete the requested action.")); Update(); }
void SurfaceAnimatorDialog::computeMultiGridAnimation() { QListWidget* fileList(m_dialog.fileList); m_referenceFrames = fileList->count(); if (m_referenceFrames < 2) return; int interpolationFrames(m_dialog.interpolationFrames->value()); double isovalue(m_dialog.isovalue->value()); double delta = 1.0/interpolationFrames; QListWidgetItem* item(fileList->item(0)); Layer::CubeData* cube(QVariantPointer<Layer::CubeData>::toPointer(item->data(Qt::UserRole))); Grid* A(cube->grid()); Grid* B(0); Grid::Size size(A->size()); Grid::DataType dataType(Grid::DataType::CubeData); Grid dAB(dataType, size); Grid t(dataType, size); Animator::Combo::DataList frames; Layer::Surface* surface; QString label; int totalSurfaces((m_referenceFrames-1)*interpolationFrames); QProgressDialog progressDialog("Calculating surfaces", "Cancel", 0, totalSurfaces, this); progressDialog.setWindowModality(Qt::WindowModal); int totalProgress(0); progressDialog.setValue(totalProgress); // loop over grids for (int i = 1; i < m_referenceFrames; ++i) { if (progressDialog.wasCanceled()) return; Data::Geometry const& geomA(cube->geometry()); item = fileList->item(i); cube = QVariantPointer<Layer::CubeData>::toPointer(item->data(Qt::UserRole)); Data::Geometry const& geomB(cube->geometry()); //qDebug() << "first geom"; //geomA.dump(); //qDebug() << "second geom"; //geomB.dump(); // Geometry displacements QList<Vec> displacements; for (int a = 0; a < geomA.nAtoms(); ++a) { Vec d(geomB.position(a)-geomA.position(a)); displacements.append(d); } // Grid displacements B = cube->grid(); t = (*A); dAB = (*B); dAB -= t; surface = calculateSurface(&dAB, isovalue); surface->setText("Difference Surface"); cube->appendLayer(surface); dAB *= delta; // loop over interpolation Frames for (int j = 0; j < interpolationFrames; ++j) { Data::Geometry geomT; for (int a = 0; a < geomA.nAtoms(); ++a) { double step = (double)j/(double)interpolationFrames; Vec d(geomA.position(a) + step*displacements[a]); geomT.append(geomA.atomicNumber(a), d); } surface = calculateSurface(&t, isovalue); frames.append(new Animator::Combo::Data(geomT, surface)); label = (j == 0) ? "Cube Data " + QString::number(i) : "Interpolation Frame " + QString::number(j); surface->setText(label); cube->appendLayer(surface); ++totalProgress; progressDialog.setValue(totalProgress); if (progressDialog.wasCanceled()) return; t += dAB; // increment the interpolation grid } A = B; } // Take care of the final reference frame surface = calculateSurface(B, isovalue); surface->setText("Cube Data " + QString::number(m_referenceFrames)); cube->appendLayer(surface); frames.append(new Animator::Combo::Data(cube->geometry(), surface)); m_animator = new Animator::Combo(m_molecule, frames, interpolationFrames, m_speed); connect(m_animator, SIGNAL(finished()), this, SLOT(animationStopped())); m_dialog.playbackBox->setEnabled(true); }
void qAnimationDlg::render() { QString outputFilename = outputFileLineEdit->text(); //save to persistent settings { QSettings settings; settings.beginGroup("qAnimation"); settings.setValue("filename", outputFilename); settings.endGroup(); } setEnabled(false); //reset the interpolators and count the total number of frames int frameCount = countFrameAndResetInterpolators(); //show progress dialog QProgressDialog progressDialog(QString("Frames: %1").arg(frameCount), "Cancel", 0, frameCount, this); progressDialog.setWindowTitle("Render"); progressDialog.show(); QApplication::processEvents(); #ifdef QFFMPEG_SUPPORT //get original viewport size QSize originalViewSize = m_view3d->size(); //hack: as the encoder requires that the video dimensions are multiples of 8, we resize the window a little bit... { //find the nearest multiples of 8 QSize customSize = originalViewSize; if (originalViewSize.width() % 8 || originalViewSize.height() % 8) { if (originalViewSize.width() % 8) customSize.setWidth((originalViewSize.width() / 8 + 1) * 8); if (originalViewSize.height() % 8) customSize.setHeight((originalViewSize.height() / 8 + 1) * 8); m_view3d->resize(customSize); QApplication::processEvents(); } } int bitrate = bitrateSpinBox->value(); int gop = 12; QVideoEncoder encoder(outputFilename, m_view3d->width(), m_view3d->height(), bitrate, gop, static_cast<unsigned>(fpsSpinBox->value())); QString errorString; if (!encoder.open(&errorString)) { QMessageBox::critical(this, "Error", QString("Failed to open file for output: %1").arg(errorString)); setEnabled(true); return; } #endif int frameIndex = 0; bool success = true; for ( size_t i=0; i<m_videoSteps.size(); ++i ) { VideoStepItem& currentVideoStep = m_videoSteps[i]; cc2DViewportObject current_params; while ( currentVideoStep.interpolator.nextView( current_params ) ) { applyViewport ( ¤t_params ); //render to image QImage image = m_view3d->renderToImage(1.0 , true, false, true ); ++frameIndex; if (image.isNull()) { QMessageBox::critical(this, "Error", "Failed to grab the screen!"); success = false; break; } #ifdef QFFMPEG_SUPPORT if (!encoder.encodeImage(image, &errorString)) { QMessageBox::critical(this, "Error", QString("Failed to encode frame #%1: %2").arg(frameIndex).arg(errorString)); success = false; break; } #else QString filename = QString("frame_%1.png").arg(frameIndex,6,10,QChar('0')); QString fullPath = QDir(outputFilename).filePath(filename); if (!image.save(fullPath)) { QMessageBox::critical(this, "Error", QString("Failed to save frame #%1").arg(frameIndex)); success = false; break; } #endif progressDialog.setValue(frameIndex); QApplication::processEvents(); if (progressDialog.wasCanceled()) { QMessageBox::warning(this, "Warning", QString("Process has been cancelled")); success = false; break; } } if (!success) { break; } } #ifdef QFFMPEG_SUPPORT encoder.close(); //hack: restore original size m_view3d->resize(originalViewSize); QApplication::processEvents(); #endif progressDialog.hide(); QApplication::processEvents(); if (success) { QMessageBox::information(this, "Job done", "The animation has been saved successfully"); } setEnabled(true); }
void QgsGPSPlugin::convertGPSFile( const QString& inputFileName, int convertType, const QString& outputFileName, const QString& layerName ) { // what features does the user want to import? QStringList convertStrings; switch ( convertType ) { case 0: convertStrings << QStringLiteral( "-x" ) << QStringLiteral( "transform,wpt=rte,del" ); break; case 1: convertStrings << QStringLiteral( "-x" ) << QStringLiteral( "transform,rte=wpt,del" ); break; case 2: convertStrings << QStringLiteral( "-x" ) << QStringLiteral( "transform,trk=wpt,del" ); break; case 3: convertStrings << QStringLiteral( "-x" ) << QStringLiteral( "transform,wpt=trk,del" ); break; default: QgsDebugMsg( "Illegal conversion index!" ); return; } // try to start the gpsbabel process QStringList babelArgs; babelArgs << mBabelPath << QStringLiteral( "-i" ) << QStringLiteral( "gpx" ) << QStringLiteral( "-f" ) << QStringLiteral( "\"%1\"" ).arg( inputFileName ) << convertStrings << QStringLiteral( "-o" ) << QStringLiteral( "gpx" ) << QStringLiteral( "-F" ) << QStringLiteral( "\"%1\"" ).arg( outputFileName ); QgsDebugMsg( QString( "Conversion command: " ) + babelArgs.join( "|" ) ); QProcess babelProcess; babelProcess.start( babelArgs.join( QStringLiteral( " " ) ) ); if ( !babelProcess.waitForStarted() ) { QMessageBox::warning( nullptr, tr( "Could not start process" ), tr( "Could not start GPSBabel!" ) ); return; } // wait for gpsbabel to finish (or the user to cancel) QProgressDialog progressDialog( tr( "Importing data..." ), tr( "Cancel" ), 0, 0 ); progressDialog.setWindowModality( Qt::WindowModal ); for ( int i = 0; babelProcess.state() == QProcess::Running; ++i ) { progressDialog.setValue( i / 64 ); if ( progressDialog.wasCanceled() ) return; } // did we get any data? if ( babelProcess.exitStatus() != 0 ) { QString babelError( babelProcess.readAllStandardError() ); QString errorMsg( tr( "Could not convert data from %1!\n\n" ) .arg( inputFileName ) ); errorMsg += babelError; QMessageBox::warning( nullptr, tr( "Error converting data" ), errorMsg ); return; } // add the layer switch ( convertType ) { case 0: case 3: emit drawVectorLayer( outputFileName + "?type=waypoint", layerName, QStringLiteral( "gpx" ) ); break; case 1: emit drawVectorLayer( outputFileName + "?type=route", layerName, QStringLiteral( "gpx" ) ); break; case 2: emit drawVectorLayer( outputFileName + "?type=track", layerName, QStringLiteral( "gpx" ) ); break; default: QgsDebugMsg( "Illegal conversion index!" ); return; } emit closeGui(); }
void CGameListCtrl::CompressSelection(bool _compress) { std::vector<const GameListItem*> items_to_compress; bool wii_compression_warning_accepted = false; for (const GameListItem* iso : GetAllSelectedISOs()) { // Don't include items that we can't do anything with if (iso->GetPlatform() != DiscIO::IVolume::GAMECUBE_DISC && iso->GetPlatform() != DiscIO::IVolume::WII_DISC) continue; if (iso->GetBlobType() != DiscIO::BlobType::PLAIN && iso->GetBlobType() != DiscIO::BlobType::GCZ) continue; items_to_compress.push_back(iso); // Show the Wii compression warning if it's relevant and it hasn't been shown already if (!wii_compression_warning_accepted && _compress && !iso->IsCompressed() && iso->GetPlatform() == DiscIO::IVolume::WII_DISC) { if (WiiCompressWarning()) wii_compression_warning_accepted = true; else return; } } wxString dirHome; wxGetHomeDir(&dirHome); wxDirDialog browseDialog(this, _("Browse for output directory"), dirHome, wxDD_DEFAULT_STYLE | wxDD_DIR_MUST_EXIST); if (browseDialog.ShowModal() != wxID_OK) return; bool all_good = true; { wxProgressDialog progressDialog( _compress ? _("Compressing ISO") : _("Decompressing ISO"), _("Working..."), 1000, // Arbitrary number that's larger than the dialog's width in pixels this, wxPD_APP_MODAL | wxPD_CAN_ABORT | wxPD_ELAPSED_TIME | wxPD_ESTIMATED_TIME | wxPD_REMAINING_TIME | wxPD_SMOOTH ); CompressionProgress progress(0, items_to_compress.size(), "", &progressDialog); for (const GameListItem* iso : items_to_compress) { if (!iso->IsCompressed() && _compress) { std::string FileName; SplitPath(iso->GetFileName(), nullptr, &FileName, nullptr); progress.current_filename = FileName; FileName.append(".gcz"); std::string OutputFileName; BuildCompleteFilename(OutputFileName, WxStrToStr(browseDialog.GetPath()), FileName); if (File::Exists(OutputFileName) && wxMessageBox( wxString::Format(_("The file %s already exists.\nDo you wish to replace it?"), StrToWxStr(OutputFileName)), _("Confirm File Overwrite"), wxYES_NO) == wxNO) continue; all_good &= DiscIO::CompressFileToBlob(iso->GetFileName(), OutputFileName, (iso->GetPlatform() == DiscIO::IVolume::WII_DISC) ? 1 : 0, 16384, &MultiCompressCB, &progress); } else if (iso->IsCompressed() && !_compress) { std::string FileName; SplitPath(iso->GetFileName(), nullptr, &FileName, nullptr); progress.current_filename = FileName; if (iso->GetPlatform() == DiscIO::IVolume::WII_DISC) FileName.append(".iso"); else FileName.append(".gcm"); std::string OutputFileName; BuildCompleteFilename(OutputFileName, WxStrToStr(browseDialog.GetPath()), FileName); if (File::Exists(OutputFileName) && wxMessageBox( wxString::Format(_("The file %s already exists.\nDo you wish to replace it?"), StrToWxStr(OutputFileName)), _("Confirm File Overwrite"), wxYES_NO) == wxNO) continue; all_good &= DiscIO::DecompressBlobToFile(iso->GetFileName().c_str(), OutputFileName.c_str(), &MultiCompressCB, &progress); } progress.items_done++; } } if (!all_good) WxUtils::ShowErrorDialog(_("Dolphin was unable to complete the requested action.")); Update(); }
void QgsGPSPlugin::uploadToGPS( QgsVectorLayer* gpxLayer, const QString& device, const QString& port ) { const QString& source( gpxLayer->dataProvider()->dataSourceUri() ); // what kind of data does the user want to upload? QString typeArg, features; if ( source.right( 8 ) == QLatin1String( "waypoint" ) ) { typeArg = QStringLiteral( "-w" ); features = QStringLiteral( "waypoints" ); } else if ( source.right( 5 ) == QLatin1String( "route" ) ) { typeArg = QStringLiteral( "-r" ); features = QStringLiteral( "routes" ); } else if ( source.right( 5 ) == QLatin1String( "track" ) ) { typeArg = QStringLiteral( "-t" ); features = QStringLiteral( "tracks" ); } else { QgsDebugMsg( source.right( 8 ) ); assert( false ); } // try to start the gpsbabel process QStringList babelArgs = mDevices[device]->exportCommand( mBabelPath, typeArg, source.left( source.lastIndexOf( '?' ) ), port ); if ( babelArgs.isEmpty() ) { QMessageBox::warning( nullptr, tr( "Not supported" ), tr( "This device does not support uploading of %1." ) .arg( features ) ); return; } QgsDebugMsg( QString( "Upload command: " ) + babelArgs.join( "|" ) ); QProcess babelProcess; babelProcess.start( babelArgs.join( QStringLiteral( " " ) ) ); if ( !babelProcess.waitForStarted() ) { QMessageBox::warning( nullptr, tr( "Could not start process" ), tr( "Could not start GPSBabel!" ) ); return; } // wait for gpsbabel to finish (or the user to cancel) QProgressDialog progressDialog( tr( "Uploading data..." ), tr( "Cancel" ), 0, 0 ); progressDialog.setWindowModality( Qt::WindowModal ); for ( int i = 0; babelProcess.state() == QProcess::Running; ++i ) { progressDialog.setValue( i / 64 ); if ( progressDialog.wasCanceled() ) return; } // did we get an error? if ( babelProcess.exitStatus() != 0 ) { QString babelError( babelProcess.readAllStandardError() ); QString errorMsg( tr( "Error while uploading data to GPS!\n\n" ) ); errorMsg += babelError; QMessageBox::warning( nullptr, tr( "Error uploading data" ), errorMsg ); return; } // everything was OK, remember this device for next time QSettings settings; settings.setValue( QStringLiteral( "/Plugin-GPS/lastuldevice" ), device ); settings.setValue( QStringLiteral( "/Plugin-GPS/lastulport" ), port ); emit closeGui(); }
void QgsGPSPlugin::downloadFromGPS( const QString& device, const QString& port, bool downloadWaypoints, bool downloadRoutes, bool downloadTracks, const QString& outputFileName, const QString& layerName ) { // what does the user want to download? QString typeArg, features; if ( downloadWaypoints ) { typeArg = QStringLiteral( "-w" ); features = QStringLiteral( "waypoints" ); } else if ( downloadRoutes ) { typeArg = QStringLiteral( "-r" ); features = QStringLiteral( "routes" ); } else if ( downloadTracks ) { typeArg = QStringLiteral( "-t" ); features = QStringLiteral( "tracks" ); } // try to start the gpsbabel process QStringList babelArgs = mDevices[device]->importCommand( mBabelPath, typeArg, port, outputFileName ); if ( babelArgs.isEmpty() ) { QMessageBox::warning( nullptr, tr( "Not supported" ), tr( "This device does not support downloading of %1." ) .arg( features ) ); return; } QgsDebugMsg( QString( "Download command: " ) + babelArgs.join( "|" ) ); QProcess babelProcess; babelProcess.start( babelArgs.join( QStringLiteral( " " ) ) ); if ( !babelProcess.waitForStarted() ) { QMessageBox::warning( nullptr, tr( "Could not start process" ), tr( "Could not start GPSBabel!" ) ); return; } // wait for gpsbabel to finish (or the user to cancel) QProgressDialog progressDialog( tr( "Downloading data..." ), tr( "Cancel" ), 0, 0 ); progressDialog.setWindowModality( Qt::WindowModal ); for ( int i = 0; babelProcess.state() == QProcess::Running; ++i ) { progressDialog.setValue( i / 64 ); if ( progressDialog.wasCanceled() ) return; } // did we get any data? if ( babelProcess.exitStatus() != 0 ) { QString babelError( babelProcess.readAllStandardError() ); QString errorMsg( tr( "Could not download data from GPS!\n\n" ) ); errorMsg += babelError; QMessageBox::warning( nullptr, tr( "Error downloading data" ), errorMsg ); return; } // add the layer if ( downloadWaypoints ) emit drawVectorLayer( outputFileName + "?type=waypoint", layerName, QStringLiteral( "gpx" ) ); if ( downloadRoutes ) emit drawVectorLayer( outputFileName + "?type=route", layerName, QStringLiteral( "gpx" ) ); if ( downloadTracks ) emit drawVectorLayer( outputFileName + "?type=track", layerName, QStringLiteral( "gpx" ) ); // everything was OK, remember the device and port for next time QSettings settings; settings.setValue( QStringLiteral( "/Plugin-GPS/lastdldevice" ), device ); settings.setValue( QStringLiteral( "/Plugin-GPS/lastdlport" ), port ); emit closeGui(); }