예제 #1
0
void ValgrindRunner::traceActivity(Activity activity, const QString &buildDirCallgrind,
                                   const QString &buildDirMassif)
{
    QString activityString;
    QString qbsCommand;
    bool dryRun;
    switch (activity) {
    case ActivityResolving:
        activityString = "resolving";
        qbsCommand = "resolve";
        dryRun = false;
        break;
    case ActivityRuleExecution:
        activityString = "rule-execution";
        qbsCommand = "build";
        dryRun = true;
        break;
    case ActivityNullBuild:
        activityString = "null-build";
        qbsCommand = "build";
        dryRun = false;
        break;
    }

    const QString outFileCallgrind = m_baseOutputDir + "/outfile." + activityString + ".callgrind";
    const QString outFileMassif = m_baseOutputDir + "/outfile." + activityString + ".massif";
    QFuture<qint64> callGrindFuture = QtConcurrent::run(this, &ValgrindRunner::runCallgrind,
            qbsCommand, buildDirCallgrind, dryRun, outFileCallgrind);
    QFuture<qint64> massifFuture = QtConcurrent::run(this, &ValgrindRunner::runMassif, qbsCommand,
            buildDirMassif, dryRun, outFileMassif);
    callGrindFuture.waitForFinished();
    massifFuture.waitForFinished();
    addToResults(ValgrindResult(activity, callGrindFuture.result(), massifFuture.result()));
}
예제 #2
0
void tst_QtConcurrentRun::functor()
{
    //this test functor without result_type,  decltype need to be supported by the compiler
#ifndef Q_COMPILER_DECLTYPE
    QSKIP("Compiler do not suport decltype", SkipAll);
#else
    Functor f;
    {
        QFuture<int> fut = QtConcurrent::run(f);
        QCOMPARE(fut.result(), 42);
    }
    {
        QFuture<double> fut = QtConcurrent::run(f, 8.5, 1.8);
        QCOMPARE(fut.result(), (8.5/1.8));
    }
    {
        QFuture<int> fut = QtConcurrent::run(f, 19, 3);
        QCOMPARE(fut.result(), int(19/3));
    }
    {
        QtConcurrent::run(f, 1).waitForFinished();
        QtConcurrent::run(f, 1,2).waitForFinished();
        QtConcurrent::run(f, 1,2,3).waitForFinished();
        QtConcurrent::run(f, 1,2,3,4).waitForFinished();
        QtConcurrent::run(f, 1,2,3,4,5).waitForFinished();
    }
#endif
}
// This tests functor without result_type; decltype need to be supported by the compiler.
void tst_QtConcurrentRun::functor()
{
#ifndef Q_COMPILER_DECLTYPE
    QSKIP("Compiler does not support decltype");
#else
    Functor f;
    {
        QFuture<int> fut = QtConcurrent::run(f);
        QCOMPARE(fut.result(), 42);
    }
    {
        QFuture<double> fut = QtConcurrent::run(f, 8.5, 1.8);
        QCOMPARE(fut.result(), (8.5/1.8));
    }
    {
        QFuture<int> fut = QtConcurrent::run(f, 19, 3);
        QCOMPARE(fut.result(), int(19/3));
    }
    {
        QtConcurrent::run(f, 1).waitForFinished();
        QtConcurrent::run(f, 1,2).waitForFinished();
        QtConcurrent::run(f, 1,2,3).waitForFinished();
        QtConcurrent::run(f, 1,2,3,4).waitForFinished();
        QtConcurrent::run(f, 1,2,3,4,5).waitForFinished();
    }
#endif
}
예제 #4
0
void ImageWidget::updateImage(bool zoom, const QImage &image, bool valuesPresent[], int values[])
{
    if(zoom) {
        QImage imageNew = scaleImage(image);
        if(imageNew.isNull()) return;

#ifndef QT_NO_CONCURRENT
        QFuture<QImage> future = QtConcurrent::run(this, &ImageWidget::scaleImage, image);
        imageNew = future.result();
#else
        QImage imageNew = scaleImage(image);

#endif

        pixmap = QPixmap::fromImage(imageNew);
    } else {
        pixmap = QPixmap::fromImage(image);
    }
    for(int i=0; i<4; i++) {
        drawValues[i] = valuesPresent[i];
        if(drawValues[i]) geoValues[i] = values[i];
        else geoValues[i] = 0;
    }
    update();
}
예제 #5
0
void Integration::initEgl()
{
    Q_ASSERT(m_eglDisplay == EGL_NO_DISPLAY);
    // This variant uses Wayland as the EGL platform
    qputenv("EGL_PLATFORM", "wayland");
    m_eglDisplay = eglGetDisplay(waylandServer()->internalClientConection()->display());
    if (m_eglDisplay == EGL_NO_DISPLAY) {
        return;
    }
    // call eglInitialize in a thread to not block
    QFuture<bool> future = QtConcurrent::run([this] () -> bool {
        EGLint major, minor;
        if (eglInitialize(m_eglDisplay, &major, &minor) == EGL_FALSE) {
            return false;
        }
        EGLint error = eglGetError();
        if (error != EGL_SUCCESS) {
            return false;
        }
        return true;
    });
    // TODO: make this better
    while (!future.isFinished()) {
        waylandServer()->internalClientConection()->flush();
        QCoreApplication::processEvents(QEventLoop::WaitForMoreEvents);
    }
    if (!future.result()) {
        eglTerminate(m_eglDisplay);
        m_eglDisplay = EGL_NO_DISPLAY;
    }
}
예제 #6
0
void EditTagDialog::SetSongsFinished(QFuture<QList<Data>> future) {
  if (!SetLoading(QString())) return;

  data_ = future.result();
  if (data_.count() == 0) {
    // If there were no valid songs, disable everything
    ui_->song_list->setEnabled(false);
    ui_->tab_widget->setEnabled(false);

    // Show a summary with empty information
    UpdateSummaryTab(Song());
    ui_->tab_widget->setCurrentWidget(ui_->summary_tab);

    SetSongListVisibility(false);
    return;
  }

  // Add the filenames to the list
  for (const Data& data : data_) {
    ui_->song_list->addItem(data.current_.basefilename());
  }

  // Select all
  ui_->song_list->setCurrentRow(0);
  ui_->song_list->selectAll();

  // Hide the list if there's only one song in it
  SetSongListVisibility(data_.count() != 1);
}
예제 #7
0
void DocsetRegistry::_runQuery(const QString &query)
{
    m_cancellationToken.reset();

    QList<Docset *> enabledDocsets;

    const SearchQuery searchQuery = SearchQuery::fromString(query);
    if (searchQuery.hasKeywords()) {
        for (Docset *docset : qAsConst(m_docsets)) {
            if (searchQuery.hasKeywords(docset->keywords()))
                enabledDocsets << docset;
        }
    } else {
        enabledDocsets = docsets();
    }

    QFuture<QList<SearchResult>> queryResultsFuture
            = QtConcurrent::mappedReduced(enabledDocsets,
                                          std::bind(&Docset::search,
                                                    std::placeholders::_1,
                                                    searchQuery.query(),
                                                    std::ref(m_cancellationToken)),
                                          &MergeQueryResults);
    QList<SearchResult> results = queryResultsFuture.result();

    if (m_cancellationToken.isCanceled())
        return;

    std::sort(results.begin(), results.end());

    if (m_cancellationToken.isCanceled())
        return;

    emit searchCompleted(results);
}
예제 #8
0
파일: BinFilter.cpp 프로젝트: kod3r/trunk
CC_FILE_ERROR BinFilter::loadFile(const char* filename, ccHObject& container, bool alwaysDisplayLoadDialog/*=true*/, bool* coordinatesShiftEnabled/*=0*/, double* coordinatesShift/*=0*/)
{
	ccLog::Print("[BIN] Opening file '%s'...",filename);


	//opening file
	QFile in(filename);
	if (!in.open(QIODevice::ReadOnly))
		return CC_FERR_READING;

	uint32_t firstBytes = 0;
	if (in.read((char*)&firstBytes,4)<0)
		return CC_FERR_READING;
	bool v1 = (strncmp((char*)&firstBytes,"CCB2",4) != 0);

	if (v1)
	{
		return LoadFileV1(in,container,static_cast<unsigned>(firstBytes),alwaysDisplayLoadDialog); //firstBytes == number of scans for V1 files!
	}
	else
	{
		if (alwaysDisplayLoadDialog)
		{
			QProgressDialog pDlg(QString("Loading: %1").arg(QFileInfo(filename).fileName()),QString(),0,0/*static_cast<int>(in.size())*/);
			pDlg.setWindowTitle("BIN file");
			pDlg.show();

			//concurrent call in a separate thread
			s_file = &in;
			s_container = &container;

			QFuture<CC_FILE_ERROR> future = QtConcurrent::run(_LoadFileV2);

			while (!future.isFinished())
			{
	#if defined(CC_WINDOWS)
				::Sleep(500);
	#else
				usleep(500 * 1000);
	#endif
				if (alwaysDisplayLoadDialog)
				{
					pDlg.setValue(pDlg.value()+1);
					//pDlg.setValue(static_cast<int>(in.pos())); //DGM: in fact, the file reading part is just half of the work!
					QApplication::processEvents();
				}
			}
	
			s_file = 0;
			s_container = 0;

			return future.result();
		}
		else
		{
			return BinFilter::LoadFileV2(in,container);
		}
	}
}
예제 #9
0
void PrettyImage::ImageScaled(QFuture<QImage> future) {
  thumbnail_ = QPixmap::fromImage(future.result());
  state_ = State_Finished;

  updateGeometry();
  update();
  emit Loaded();
}
예제 #10
0
bool CatalogConnector::loadDataThreaded(IlwisObject *obj, const IOOptions &options){
    kernel()->issues()->log(QString(TR("Scanning %1")).arg(source().url(true).toString()),IssueObject::itMessage);
    QVector<std::pair<CatalogExplorer *, IOOptions>> explorers;
    for(const auto& explorer : _dataProviders){
       explorers.push_back({explorer.get(), options});
    }
    QFuture<std::vector<Resource>> res = QtConcurrent::mappedReduced(explorers,loadExplorerData, gatherData);
    res.waitForFinished();
    mastercatalog()->addItems(res.result());
    return true;
}
예제 #11
0
void windowLoadMiRNAF::on_buttonChooseMirnaF_clicked()
{
    fileNameMiRNA=QFileDialog::getOpenFileName(
                this,
                tr("Choose File"),
                "",
                "FASTA files (*.fasta);;Text files (*.txt);;All files (*)"
                );
    if(!fileNameMiRNA.isEmpty()){
        ui->progressBar->show();
        try
        {
            QFuture<bool> future = QtConcurrent::run(&QtExceptionWrapper::targetFinder_getMiRNAs,m_oTF,fileNameMiRNA.toStdString());
            //m_oTF->getMiRNAs(fileNameMiRNA.toStdString());
            this->FutureWatcher.setFuture(future);
            future.result();
            //make visible  labelFileSelectedMirna
            ui->labelFileSelectedMirna->setVisible(true);
            //change the value of labelFileSelectedMirna
            ui->labelFileSelectedMirna->setText(tr("Mirna File selected : ")+fileNameMiRNA);
            //make the button next accessible
            ui->NextAnalyzeResults->setEnabled(true);

            this->ui->progressBar->setMaximum(100);
            this->ui->progressBar->setValue(100);
        }catch(MyException const& e)
        {
            QMessageBox::warning(this,tr("Loading error"),e.what());
            //hiding labelFileSelectedMirna
            ui->labelFileSelectedMirna->setVisible(false);
            //change the value of labelFileSelectedMirna
            ui->labelFileSelectedMirna->setText(tr(""));
            //make the button next disabled
            ui->NextAnalyzeResults->setEnabled(false);
            this->ui->progressBar->hide();
        }catch(std::string const& e2)
        {
            QMessageBox::warning(this,tr("Loading error"),QString::fromStdString(e2));
            //hiding labelFileSelectedMirna
            ui->labelFileSelectedMirna->setVisible(false);
            //change the value of labelFileSelectedMirna
            ui->labelFileSelectedMirna->setText(tr(""));
            //make the button next disabled
            ui->NextAnalyzeResults->setEnabled(false);
            this->ui->progressBar->hide();
        }
    }
    else{
        QMessageBox::warning(this,tr("File selected"),tr("No file selected"));
    }

}
예제 #12
0
bool ActivitySessionData::setCurrentActivity(const QString &activityId)
{
    QFuture<bool> rv;
    QMetaObject::invokeMethod(m_activitiesProxy, "setCurrentActivity",
                              Qt::BlockingQueuedConnection,
                              Q_RETURN_ARG(QFuture<bool>, rv),
                              Q_ARG(QString, activityId));
    rv.waitForFinished();

    //TODO: this shows one of the weaknesses in the QFuture based APIs ....
    bool value = rv.results().isEmpty() ? false : rv.result();
    return value;
}
예제 #13
0
void DkThumbNailT::thumbLoaded() {
	
	QFuture<QImage> future = thumbWatcher.future();

	img = future.result();
	
	if (img.isNull() && forceLoad != force_exif_thumb)
		imgExists = false;

	fetching = false;
	DkSettings::resources.numThumbsLoading--;
	emit thumbLoadedSignal(img.isNull());
}
예제 #14
0
void DkThumbNailT::colorLoaded() {

	QFuture<QColor> future = colorWatcher.future();

	meanColor = future.result();

	if (meanColor != DkSettings::display.bgColorWidget)
		emit colorUpdated();
	else
		colorExists = false;

	fetchingColor = false;
	qDebug() << "mean color: " << meanColor;
}
void tst_QtConcurrentThreadEngine::runThroughStarter()
{
    {
        ThreadEngineStarter<QString> starter = startThreadEngine(new StringResultUser());
        QFuture<QString>  f = starter.startAsynchronously();
        QCOMPARE(f.result(), QString("Foo"));
    }

    {
        ThreadEngineStarter<QString> starter = startThreadEngine(new StringResultUser());
        QString str = starter.startBlocking();
        QCOMPARE(str, QString("Foo"));
    }
}
예제 #16
0
QDomDocument* TeamWorkApi::FutureParseResponse( QString strName, QString strXml ){
   strSomeError.clear();
   
   QFuture<QDomDocument*> objFuture = QtConcurrent::run( this, &TeamWorkApi::ParseResponse, strName, strXml );
   while( !objFuture.isFinished() )
      QCoreApplication::processEvents( QEventLoop::AllEvents, 100 );

   QDomDocument *pdomResult = objFuture.result();
   if( 0 < strSomeError.length() ){
      emit TmpmApiError( strSomeError );
      return NULL;
   }

   return pdomResult;
}
예제 #17
0
void LibraryModel::ResetAsyncQueryFinished(
    QFuture<LibraryModel::QueryResult> future) {
  const struct QueryResult result = future.result();

  BeginReset();
  root_->lazy_loaded = true;

  PostQuery(root_, result, false);

  if (init_task_id_ != -1) {
    app_->task_manager()->SetTaskFinished(init_task_id_);
    init_task_id_ = -1;
  }

  endResetModel();
}
void ImageWidget::updateImage(bool FitToSize, const QImage &image, bool valuesPresent[], int values[], const double &scaleFactor,
                              bool selectStarted, QRect selectRect, bool selectSimpleView)
{
    disconnected = false;
    selectionRect = selectRect;
    selectionStarted = selectStarted;
    simpleView = selectSimpleView;
    // in case of fit to parent widget, we calculate concurrently if possible
    if((FitToSize) || (qAbs(scaleFactor-1) > 0.01)) {
#ifndef QT_NO_CONCURRENT
        QFuture<QImage> future = QtConcurrent::run(this, &ImageWidget::scaleImage, image, scaleFactor, FitToSize);
        imageNew = future.result();
#else
        imageNew = scaleImage(image, scalefactor, FitToSize);
#endif
        // no scaling, just take the pointer
    } else {
        imageNew = image;
    }

    if(simpleView) {
        update();
        return;
    }

    for(int i=0; i<4; i++) {
        drawValues[i] = valuesPresent[i];
        if(drawValues[i]) {
            if(!FitToSize) {
                geoValues[i] = values[i] * scaleFactor;
            } else {
                double factorX = (double) this->size().width() / (double) image.size().width();
                double factorY = (double) this->size().height() /(double) image.size().height();
                double factor = qMin(factorX, factorY);
                //printf("(%d,%d) (%d,%d)  (%f,%f)\n", this->size().width(), this->size().height(),
                //                                     image.size().width(), image.size().height(),
                //                                    factorX, factorY);
                geoValues[i] = (int) (((values[i]+0.5) * factor));
                //printf("geovalues %d %f %d\n", values[i], factor, geoValues[i]);
            }
        }
        else geoValues[i] = 0;
    }
    update();
}
void Management::slaveBuildSize(int BuildID, QString buildMD5Value, int slaveId){
    Build *theBuild = getBuildByID(BuildID);

    if(theBuild ==  0){
        //this point the build does not exist
        return;
    }

    QFuture<QString> future = QtConcurrent::run(this, &Management::getBuildMD5, theBuild);
    QString currentBuildMD5Value = future.result();

    if(!buildMD5Value.compare(currentBuildMD5Value)){
        setSlaveBuildIsSame(true, slaveId, theBuild->getBuildID());
    }
    else{
        setSlaveBuildIsSame(false, slaveId, theBuild->getBuildID());
    }
}
예제 #20
0
파일: LUtils.cpp 프로젝트: Nanolx/lumina
//=============
//  LUtils Functions
//=============
int LUtils::runCmd(QString cmd, QStringList args){
  /*QProcess proc;
  proc.setProcessChannelMode(QProcess::MergedChannels);
  if(args.isEmpty()){
    proc.start(cmd);
  }else{
    proc.start(cmd, args);
  }
  //if(!proc.waitForStarted(30000)){ return 1; } //process never started - max wait of 30 seconds
  while(!proc.waitForFinished(300)){
    if(proc.state() == QProcess::NotRunning){ break; } //somehow missed the finished signal
    QCoreApplication::processEvents();
  }
  int ret = proc.exitCode();
  return ret;*/
  QFuture<QStringList> future = QtConcurrent::run(ProcessRun, cmd, args);
  return future.result()[0].toInt(); //turn it back into an integer return code
	
}
예제 #21
0
PwDatabase::ErrorCode PwDatabase::transformKey(const QByteArray& masterSeed, const QByteArray& transformSeed,
        quint64 transformRounds, const QByteArray& combinedKey, QByteArray& aesKey) {
    setPhaseProgressRawTarget(transformRounds);

    QByteArray subKey1 = Util::deepCopy(combinedKey.left(SUBKEY_SIZE));
    QByteArray subKey2 = Util::deepCopy(combinedKey.right(SUBKEY_SIZE));
    unsigned char* pSubKey1 = reinterpret_cast<unsigned char*>(subKey1.data());
    unsigned char* pSubKey2 = reinterpret_cast<unsigned char*>(subKey2.data());
    const unsigned char* pTransformSeed = reinterpret_cast<const unsigned char*>(transformSeed.constData());

    // One subkey is processed in a parallel thread,
    // another one -- synchronously here (to update the UI progress)
    QFuture<PwDatabase::ErrorCode> anotherTask = QtConcurrent::run(this, &PwDatabase::performKeyTransformRounds,
            pTransformSeed, pSubKey1, transformRounds, false);
    ErrorCode errCode = performKeyTransformRounds(pTransformSeed, pSubKey2, transformRounds, true);
    if (errCode != SUCCESS || anotherTask.result() != SUCCESS) {
        return errCode;
    }

    CryptoManager* cm = CryptoManager::instance();

    QByteArray step2key;
    step2key.append(subKey1);
    step2key.append(subKey2);
    QByteArray transformedKey;
    int ec = cm->sha256(step2key, transformedKey);
    Util::safeClear(subKey1);
    Util::safeClear(subKey2);
    Util::safeClear(step2key);
    if (ec != SB_SUCCESS)
        return KEY_TRANSFORM_ERROR_2;

    QByteArray step3key(masterSeed);
    step3key.append(transformedKey);
    ec = cm->sha256(step3key, aesKey);
    Util::safeClear(transformedKey);
    Util::safeClear(step3key);
    if (ec != SB_SUCCESS)
        return KEY_TRANSFORM_ERROR_3;

    return SUCCESS;
}
예제 #22
0
파일: BinFilter.cpp 프로젝트: kod3r/trunk
CC_FILE_ERROR BinFilter::saveToFile(ccHObject* root, const char* filename)
{
	if (!root || !filename)
		return CC_FERR_BAD_ARGUMENT;

	QFile out(filename);
	if (!out.open(QIODevice::WriteOnly))
		return CC_FERR_WRITING;

	QProgressDialog pDlg(QString("Please wait... saving in progress"),QString(),0,0);
	pDlg.setWindowTitle("BIN file");
	pDlg.setModal(true);
	pDlg.show();

	//concurrent call
	s_file = &out;
	s_container = root;

	QFuture<CC_FILE_ERROR> future = QtConcurrent::run(_SaveFileV2);

	while (!future.isFinished())
	{
#if defined(CC_WINDOWS)
		::Sleep(500);
#else
        usleep(500 * 1000);
#endif
		pDlg.setValue(pDlg.value()+1);
		QApplication::processEvents();
	}
	
	s_file = 0;
	s_container = 0;

	CC_FILE_ERROR result = future.result();

	if (result == CC_FERR_NO_ERROR)
		ccLog::Print("[BIN] File %s saved successfully",filename);

	return result;
}
예제 #23
0
CC_FILE_ERROR BinFilter::saveToFile(ccHObject* root, QString filename, SaveParameters& parameters)
{
	if (!root || filename.isNull())
		return CC_FERR_BAD_ARGUMENT;

	QFile out(filename);
	if (!out.open(QIODevice::WriteOnly))
		return CC_FERR_WRITING;

	ccProgressDialog pDlg(false, parameters.parentWidget);
	pDlg.setMethodTitle(QObject::tr("BIN file"));
	pDlg.setInfo(QObject::tr("Please wait... saving in progress"));
	pDlg.setRange(0, 0);
	pDlg.setModal(true);
	pDlg.show();

	//concurrent call
	s_file = &out;
	s_container = root;

	QFuture<CC_FILE_ERROR> future = QtConcurrent::run(_SaveFileV2);

	while (!future.isFinished())
	{
#if defined(CC_WINDOWS)
		::Sleep(500);
#else
		usleep(500 * 1000);
#endif
		pDlg.setValue(pDlg.value()+1);
		QApplication::processEvents();
	}
	
	s_file = 0;
	s_container = 0;

	CC_FILE_ERROR result = future.result();

	return result;
}
예제 #24
0
파일: LUtils.cpp 프로젝트: Nanolx/lumina
QStringList LUtils::getCmdOutput(QString cmd, QStringList args){
  /*QProcess proc;
  QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
  env.insert("LANG", "C");
  env.insert("LC_MESSAGES", "C");
  proc.setProcessEnvironment(env);
  proc.setProcessChannelMode(QProcess::MergedChannels);
  if(args.isEmpty()){
    proc.start(cmd);
  }else{
    proc.start(cmd,args);	  
  }
  //if(!proc.waitForStarted(30000)){ return QStringList(); } //process never started - max wait of 30 seconds
  while(!proc.waitForFinished(300)){
    if(proc.state() == QProcess::NotRunning){ break; } //somehow missed the finished signal
    QCoreApplication::processEvents();
  }
  QStringList out = QString(proc.readAllStandardOutput()).split("\n");
  return out;*/
  QFuture<QStringList> future = QtConcurrent::run(ProcessRun, cmd, args);
  return future.result()[1].split("\n"); //Split the return message into lines
}
예제 #25
0
void IcecastService::ParseDirectoryFinished(
    QFuture<IcecastBackend::StationList> future) {
  IcecastBackend::StationList all_stations = future.result();
  sort(all_stations.begin(), all_stations.end(),
       StationSorter<IcecastBackend::Station>());
  // Remove duplicates by name. These tend to be multiple URLs for the same
  // station.
  IcecastBackend::StationList::iterator it =
      unique(all_stations.begin(), all_stations.end(),
             StationEquality<IcecastBackend::Station>());
  all_stations.erase(it, all_stations.end());

  // Cluster stations by genre.
  QMultiHash<QString, IcecastBackend::Station*> genres;

  // Add stations.
  for (int i = 0; i < all_stations.count(); ++i) {
    IcecastBackend::Station& s = all_stations[i];
    genres.insert(s.genre, &s);
  }

  QSet<QString> genre_set = genres.keys().toSet();

  // Merge genres with only 1 or 2 stations into "Other".
  for (const QString& genre : genre_set) {
    if (genres.count(genre) < 3) {
      const QList<IcecastBackend::Station*>& small_genre = genres.values(genre);
      for (IcecastBackend::Station* s : small_genre) {
        s->genre = "Other";
      }
    }
  }

  backend_->ClearAndAddStations(all_stations);

  app_->task_manager()->SetTaskFinished(load_directory_task_id_);
  load_directory_task_id_ = 0;
}
예제 #26
0
void DeviceProperties::UpdateFormatsFinished(QFuture<bool> future) {
    updating_formats_ = false;

    if (!future.result()) {
        supported_formats_.clear();
    }

    // Hide widgets if there are no supported types
    ui_->supported_formats_container->setVisible(!supported_formats_.isEmpty());
    ui_->transcode_unsupported->setEnabled(!supported_formats_.isEmpty());

    if (ui_->transcode_unsupported->isChecked() && supported_formats_.isEmpty()) {
        ui_->transcode_off->setChecked(true);
    }

    // Populate supported types list
    ui_->supported_formats->clear();
    for (Song::FileType type : supported_formats_) {
        QListWidgetItem* item = new QListWidgetItem(Song::TextForFiletype(type));
        ui_->supported_formats->addItem(item);
    }
    ui_->supported_formats->sortItems();

    // Set the format combobox item
    TranscoderPreset preset = Transcoder::PresetForFileType(
                                  Song::FileType(index_.data(DeviceManager::Role_TranscodeFormat).toInt()));
    if (preset.type_ == Song::Type_Unknown) {
        // The user hasn't chosen a format for this device yet, so work our way down
        // a list of some preferred formats, picking the first one that is supported
        preset = Transcoder::PresetForFileType(
                     Transcoder::PickBestFormat(supported_formats_));
    }
    ui_->transcode_format->setCurrentIndex(
        ui_->transcode_format->findText(preset.name_));

    ui_->formats_stack->setCurrentWidget(ui_->formats_page);
}
예제 #27
0
T QxrdResultSerializer<T>::dequeue()
{
  QcepMutexLocker lock(__FILE__, __LINE__, &m_Mutex);

  if (m_Results.size() > 0) {
    QFuture<T> val = m_Results.dequeue();

    if (m_Results.size() > 0) {
      m_Watcher.setFuture(m_Results[0]);
    }

    if (m_Counter) {
      m_Counter->incValue(-1);
    }

    return val.result();
  } else {
    if (m_Counter) {
      m_Counter->setValue(0);
    }

    return T();
  }
}
예제 #28
0
CC_FILE_ERROR BinFilter::loadFile(QString filename, ccHObject& container, LoadParameters& parameters)
{
	ccLog::Print(QString("[BIN] Opening file '%1'...").arg(filename));

	//opening file
	QFile in(filename);
	if (!in.open(QIODevice::ReadOnly))
		return CC_FERR_READING;

	uint32_t firstBytes = 0;
	if (in.read((char*)&firstBytes,4) < 0)
		return CC_FERR_READING;
	bool v1 = (strncmp((char*)&firstBytes,"CCB",3) != 0);

	if (v1)
	{
		return LoadFileV1(in, container, static_cast<unsigned>(firstBytes), parameters); //firstBytes == number of scans for V1 files!
	}
	else
	{
		//Since ver 2.5.2, the 4th character of the header corresponds to 'load flags'
		int flags = 0;
		{
			QChar c(reinterpret_cast<char*>(&firstBytes)[3]);
			bool ok;
			flags = QString(c).toInt(&ok);
			if (!ok || flags > 8)
			{
				ccLog::Error(QString("Invalid file header (4th byte is '%1'?!)").arg(c));
				return CC_FERR_WRONG_FILE_TYPE;
			}
		}

		//if (sizeof(PointCoordinateType) == 8 && strncmp((char*)&firstBytes,"CCB3",4) != 0)
		//{
		//	QMessageBox::information(0, QString("Wrong version"), QString("This file has been generated with the standard 'float' version!\nAt this time it cannot be read with the 'double' version."),QMessageBox::Ok);
		//	return CC_FERR_WRONG_FILE_TYPE;
		//}
		//else if (sizeof(PointCoordinateType) == 4 && strncmp((char*)&firstBytes,"CCB2",4) != 0)
		//{
		//	QMessageBox::information(0, QString("Wrong version"), QString("This file has been generated with the new 'double' version!\nAt this time it cannot be read with the standard 'float' version."),QMessageBox::Ok);
		//	return CC_FERR_WRONG_FILE_TYPE;
		//}

		if (parameters.alwaysDisplayLoadDialog)
		{
			ccProgressDialog pDlg(false, parameters.parentWidget);
			pDlg.setMethodTitle(QObject::tr("BIN file"));
			pDlg.setInfo(QObject::tr("Loading: %1").arg(QFileInfo(filename).fileName()));
			pDlg.setRange(0, 0);
			pDlg.show();

			//concurrent call in a separate thread
			s_file = &in;
			s_container = &container;
			s_flags = flags;

			QFuture<CC_FILE_ERROR> future = QtConcurrent::run(_LoadFileV2);

			while (!future.isFinished())
			{
	#if defined(CC_WINDOWS)
				::Sleep(500);
	#else
				usleep(500 * 1000);
	#endif
				pDlg.setValue(pDlg.value()+1);
				//pDlg.setValue(static_cast<int>(in.pos())); //DGM: in fact, the file reading part is just half of the work!
				QApplication::processEvents();
			}
	
			s_file = 0;
			s_container = 0;

			return future.result();
		}
		else
		{
			return BinFilter::LoadFileV2(in,container,flags);
		}
	}
}
//! [1]
extern void aFunctionWithArguments(int arg1, double arg2, const QString &string);

int integer = ...;
double floatingPoint = ...;
QString string = ...;

QFuture<void> future = QtConcurrent::run(aFunctionWithArguments, integer, floatingPoint, string);
//! [1]


//! [2]
extern QString functionReturningAString();
QFuture<QString> future = QtConcurrent::run(functionReturningAString);
...
QString result = future.result();
//! [2]


//! [3]
extern QString someFunction(const QByteArray &input);

QByteArray bytearray = ...;

QFuture<QString> future = QtConcurrent::run(someFunction, bytearray);
...
QString result = future.result();
//! [3]


//! [4]
void tst_QtConcurrentRun::returnValue()
{
    QFuture<int> f;

    f = run(F(returnInt0));
    QCOMPARE(f.result(), 10);

    A a;
    f = run(&a, F(&A::member0));
    QCOMPARE(f.result(), 10);

    f = run(&a, F(&A::member1), 20);
    QCOMPARE(f.result(), 20);

    f = run(a, F(&A::member0));
    QCOMPARE(f.result(), 10);

    f = run(a, F(&A::member1), 20);
    QCOMPARE(f.result(), 20);

    f = run(a);
    QCOMPARE(f.result(), 10);

    f = run(&a);
    QCOMPARE(f.result(), 10);

    f = run(a, 20);
    QCOMPARE(f.result(), 20);

    f = run(&a, 20);
    QCOMPARE(f.result(), 20);

    const AConst aConst = AConst();
    f = run(&aConst, &AConst::member0);
    QCOMPARE(f.result(), 10);

    f = run(&aConst, F(&AConst::member1), 20);
    QCOMPARE(f.result(), 20);

    f = run(aConst, F(&AConst::member0));
    QCOMPARE(f.result(), 10);

    f = run(aConst, F(&AConst::member1), 20);
    QCOMPARE(f.result(), 20);

    f = run(aConst);
    QCOMPARE(f.result(), 10);

    f = run(&aConst);
    QCOMPARE(f.result(), 10);

    f = run(aConst, 20);
    QCOMPARE(f.result(), 20);

    f = run(&aConst, 20);
    QCOMPARE(f.result(), 20);
}