void QmlProfilerTimelineModel::clear()
{
    TimelineModel::clear();
    updateProgress(0, 1);
}
/**
 *  this is the real workhorse.
 * maybe we should not call this directly, but instead from doWork ?
 */
void RenderTask_sV::slotContinueRendering()
{
    qDebug()<<"Starting rendering process in Thread "<<thread()->currentThreadId();   

    /* real workhorse, need to account for exporting */
    setupProgress(trUtf8("Rendering Slow-Mo …"), 2* int(m_prefs.fps().fps() * (m_timeEnd-m_timeStart)));
        
    //TODO: initialize
    m_stopwatch.start();
    
    m_nextFrameTime=m_timeStart;
    
    int framesBefore;
    qreal snapped = m_project->snapToOutFrame(m_nextFrameTime, false, m_prefs.fps(), &framesBefore);
    qDebug() << "Frame snapping in from " << m_nextFrameTime << " to " << snapped;
    m_nextFrameTime = snapped;
    
    Q_ASSERT(int((m_nextFrameTime - m_project->nodes()->startTime()) * m_prefs.fps().fps() + .5) == framesBefore);
    
    try {
    	m_renderTarget->openRenderTarget();
    } catch (Error_sV &err) {
            m_stopRendering = true;
            emit signalRenderingAborted(tr("Rendering aborted.") + " " + err.message());
            return;
    }
    
    // render loop
    // TODO: add more threading here
    while(m_nextFrameTime<m_timeEnd) {
    	    QCoreApplication::processEvents();
    	    
        // Checks if the process should be aborted
        mutex.lock();
        bool abort = m_stopRendering;
        mutex.unlock();
        
        if (abort) {
        	// user stop the process
            qDebug()<<"Aborting Rendering process in Thread "<<thread()->currentThreadId();
						m_renderTimeElapsed = m_stopwatch.elapsed();
            emit signalRenderingStopped(QTime().addMSecs(m_renderTimeElapsed).toString("hh:mm:ss"));
        	qDebug() << "Rendering stopped after " << QTime().addMSecs(m_renderTimeElapsed).toString("hh:mm:ss");
            break;
        }
        
        // do the work
        int outputFrame = (m_nextFrameTime - m_project->nodes()->startTime()) * m_prefs.fps().fps() + .5;
        qreal srcTime = m_project->nodes()->sourceTime(m_nextFrameTime);
        
        qDebug() << "Rendering frame number " << outputFrame << " @" << m_nextFrameTime << " from source time " << srcTime;
        updateMessage(tr("Rendering frame %1 @ %2 s  from input position: %3 s (frame %4)")
                            .arg( QString::number(outputFrame),QString::number(m_nextFrameTime),
                                  QString::number(srcTime),
                                  QString::number(srcTime*m_project->frameSource()->fps()->fps())
                             ) );
           
    	 try {
                QImage rendered = m_project->render(m_nextFrameTime, m_prefs);

                m_renderTarget->slotConsumeFrame(rendered, outputFrame);
                m_nextFrameTime = m_nextFrameTime + 1/m_prefs.fps().fps();

                updateProgress( (m_nextFrameTime-m_timeStart) * m_prefs.fps().fps() );
                
            } catch (FlowBuildingError &err) {
                m_stopRendering = true;
                emit signalRenderingAborted(err.message());
            } catch (InterpolationError &err) {
                updateMessage(err.message());
            }
        
        
    } /* while */
    
    
    // Checks if the process should be aborted
    mutex.lock();
    bool abort = m_stopRendering;
    mutex.unlock();
        
    if (abort) {
						qDebug() << "Rendering : aborting";
						updateMessage(tr("Rendering : aborting"));
	  } else {
						//TODO: closing rendering project
						qDebug() << "Rendering : exporting";
						updateMessage(tr("Rendering : exporting"));
						m_renderTarget->closeRenderTarget();
	  }

		m_renderTimeElapsed = m_stopwatch.elapsed();
		qDebug() << "time : " << m_renderTimeElapsed;
		emit signalRenderingFinished(QTime(0,0).addMSecs(m_renderTimeElapsed).toString("hh:mm:ss"));
		qDebug() << "Rendering stopped after " << QTime(0,0).addMSecs(m_renderTimeElapsed).toString("hh:mm:ss");
   
		qDebug()<<"Rendering process finished in Thread "<<thread()->currentThreadId();

    // Set _working to false, meaning the process can't be aborted anymore.
    mutex.lock();
    _working = false;
    mutex.unlock();
}
示例#3
0
void NGSD::annotate(VariantList& variants, QString filename)
{
	initProgress("NGSD annotation", true);

	//get sample ids
	QString s_id = sampleId(filename, false);
	QString ps_id = processedSampleId(filename, false);
	QString sys_id = getValue("SELECT processing_system_id FROM processed_sample WHERE id='" + processedSampleId(filename, false) + "'").toString();

	//check if we could determine the sample
	bool found_in_db = true;
	if (s_id=="" || ps_id=="" || sys_id=="")
	{
		Log::warn("Could not find processed sample in NGSD by name '" + filename + "'. Annotation will be incomplete because processing system could not be determined!");
		found_in_db = false;
	}

	//get sample ids that have processed samples with the same processing system (not same sample, variants imported, same processing system, good quality of sample, not tumor)
	QSet<int> sys_sample_ids;
	SqlQuery tmp = getQuery();
	tmp.exec("SELECT DISTINCT s.id FROM processed_sample as ps, sample s WHERE ps.processing_system_id='" + sys_id + "' AND ps.sample_id=s.id AND s.tumor='0' AND s.quality='good' AND s.id!='" + s_id + "' AND (SELECT count(id) FROM detected_variant as dv WHERE dv.processed_sample_id = ps.id)>0");
	while(tmp.next())
	{
		sys_sample_ids.insert(tmp.value(0).toInt());
	}

	//remove all NGSD-specific columns
	QList<VariantAnnotationHeader> headers = variants.annotations();
	foreach(const VariantAnnotationHeader& header, headers)
	{
		if (header.name().startsWith("ihdb_"))
		{
			removeColumnIfPresent(variants, header.name(), true);
		}
	}
	removeColumnIfPresent(variants, "classification", true);
	removeColumnIfPresent(variants, "classification_comment", true);
	removeColumnIfPresent(variants, "validated", true);
	removeColumnIfPresent(variants, "comment", true);

	//get required column indices
	QString num_samples = QString::number(sys_sample_ids.count());
	int ihdb_hom_idx = addColumn(variants, "ihdb_hom", "Homozygous variant counts in NGSD for the same processing system (" + num_samples + " samples).");
	int ihdb_het_idx = addColumn(variants, "ihdb_het", "Heterozyous variant counts in NGSD for the same processing system (" + num_samples + " samples).");
	int ihdb_wt_idx  = addColumn(variants, "ihdb_wt", "Wildtype variant counts in NGSD for the same processing system (" + num_samples + " samples).");
	int ihdb_all_hom_idx = addColumn(variants, "ihdb_allsys_hom", "Homozygous variant counts in NGSD independent of the processing system.");
	int ihdb_all_het_idx =  addColumn(variants, "ihdb_allsys_het", "Heterozygous variant counts in NGSD independent of the processing system.");
	int class_idx = addColumn(variants, "classification", "Classification from the NGSD.");
	int clacom_idx = addColumn(variants, "classification_comment", "Classification comment from the NGSD.");
	int valid_idx = addColumn(variants, "validated", "Validation information from the NGSD. Validation results of other samples are listed in brackets!");
	if (variants.annotationIndexByName("comment", true, false)==-1) addColumn(variants, "comment", "Comments from the NGSD. Comments of other samples are listed in brackets!");
	int comment_idx = variants.annotationIndexByName("comment", true, false);

	//(re-)annotate the variants
	SqlQuery query = getQuery();
	for (int i=0; i<variants.count(); ++i)
	{
		//QTime timer;
		//timer.start();

		//variant id
		Variant& v = variants[i];
		QByteArray v_id = variantId(v, false).toLatin1();

		//variant classification
		QVariant classification = getValue("SELECT class FROM variant_classification WHERE variant_id='" + v_id + "'", true);
		if (!classification.isNull())
		{
			v.annotations()[class_idx] = classification.toByteArray().replace("n/a", "");
			v.annotations()[clacom_idx] = getValue("SELECT comment FROM variant_classification WHERE variant_id='" + v_id + "'", true).toByteArray().replace("\n", " ").replace("\t", " ");
		}
		//int t_v = timer.elapsed();
		//timer.restart();

		//detected variant infos
		int dv_id = -1;
		QByteArray comment = "";
		if (found_in_db)
		{
			query.exec("SELECT id, comment FROM detected_variant WHERE processed_sample_id='" + ps_id + "' AND variant_id='" + v_id + "'");
			if (query.size()==1)
			{
				query.next();
				dv_id = query.value(0).toInt();
				comment = query.value(1).toByteArray();
			}
		}

		//validation info
		int vv_id = -1;
		QByteArray val_status = "";
		if (found_in_db)
		{
			query.exec("SELECT id, status FROM variant_validation WHERE sample_id='" + s_id + "' AND variant_id='" + v_id + "'");
			if (query.size()==1)
			{
				query.next();
				vv_id = query.value(0).toInt();
				val_status = query.value(1).toByteArray().replace("n/a", "");
			}
		}

		//int t_dv = timer.elapsed();
		//timer.restart();

		//validation info other samples
		int tps = 0;
		int fps = 0;
		query.exec("SELECT id, status FROM variant_validation WHERE variant_id='"+v_id+"' AND status!='n/a'");
		while(query.next())
		{
			if (query.value(0).toInt()==vv_id) continue;
			if (query.value(1).toByteArray()=="true positive") ++tps;
			else if (query.value(1).toByteArray()=="false positive") ++fps;
		}
		if (tps>0 || fps>0)
		{
			if (val_status=="") val_status = "n/a";
			val_status += " (" + QByteArray::number(tps) + "xTP, " + QByteArray::number(fps) + "xFP)";
		}
		//int t_val = timer.elapsed();
		//timer.restart();

		//comments other samples
		QList<QByteArray> comments;
		query.exec("SELECT id, comment FROM detected_variant WHERE variant_id='"+v_id+"' AND comment IS NOT NULL");
		while(query.next())
		{
			if (query.value(0).toInt()==dv_id) continue;
			QByteArray tmp = query.value(1).toByteArray().trimmed();
			if (tmp!="") comments.append(tmp);
		}
		if (comments.size()>0)
		{
			if (comment=="") comment = "n/a";
			comment += " (";
			for (int i=0; i<comments.count(); ++i)
			{
				if (i>0)
				{
					comment += ", ";
				}
				comment += comments[i];
			}
			comment += ")";
		}
		//int t_com = timer.elapsed();
		//timer.restart();

		//genotype counts
		int allsys_hom_count = 0;
		int allsys_het_count = 0;
		int sys_hom_count = 0;
		int sys_het_count = 0;
		QSet<int> s_ids_done;
		int s_id_int = s_id.toInt();
		query.exec("SELECT dv.genotype, ps.sample_id FROM detected_variant as dv, processed_sample ps WHERE dv.processed_sample_id=ps.id AND dv.variant_id='" + v_id + "'");
		while(query.next())
		{
			//skip this sample id
			int current_sample = query.value(1).toInt();
			if (current_sample==s_id_int) continue;

			//skip already seen samples (there could be several processings of the same sample because of different processing systems or because of experment repeats due to quality issues)
			if (s_ids_done.contains(current_sample)) continue;
			s_ids_done.insert(current_sample);

			QByteArray current_geno = query.value(0).toByteArray();
			if (current_geno=="hom")
			{
				++allsys_hom_count;
				if (sys_sample_ids.contains(current_sample))
				{
					++sys_hom_count;
				}
			}
			else if (current_geno=="het")
			{
				++allsys_het_count;
				if (sys_sample_ids.contains(current_sample))
				{
					++sys_het_count;
				}
			}
		}
		//qDebug() << (v.isSNV() ? "S" : "I") << query.size() << t_v << t_dv << t_val << t_com << timer.elapsed();

		v.annotations()[ihdb_all_hom_idx] = QByteArray::number(allsys_hom_count);
		v.annotations()[ihdb_all_het_idx] = QByteArray::number(allsys_het_count);
		if (found_in_db)
		{
			v.annotations()[ihdb_hom_idx] = QByteArray::number((double)sys_hom_count / sys_sample_ids.count(), 'f', 4);
			v.annotations()[ihdb_het_idx] =  QByteArray::number((double)sys_het_count / sys_sample_ids.count(), 'f', 4);
			v.annotations()[ihdb_wt_idx] =  QByteArray::number((double)(sys_sample_ids.count() - sys_hom_count - sys_het_count) / sys_sample_ids.count(), 'f', 4);
			v.annotations()[valid_idx] = val_status;
			v.annotations()[comment_idx] = comment.replace("\n", " ").replace("\t", " ");
		}
		else
		{
			v.annotations()[ihdb_hom_idx] = "n/a";
			v.annotations()[ihdb_het_idx] = "n/a";
			v.annotations()[ihdb_wt_idx] = "n/a";
			v.annotations()[valid_idx] = "n/a";
			v.annotations()[comment_idx] = "n/a";
		}

		emit updateProgress(100*i/variants.count());
	}
}
示例#4
0
QString GraphExport::generateCSV(quint32 limit)
{
    const quint32 start = ui->sampleStartBox->value();
    quint32 end = ui->sampleEndBox->value();
    if(end - start > limit)
        end = start + limit;

    std::vector<GraphCurve*> order;
    for(int i = 0; i < ui->colList->count(); ++i)
    {
        QListWidgetItem *item = ui->colList->item(i);
        if(item->checkState() != Qt::Checked)
            continue;

        int idx = item->data(Qt::UserRole).toInt();
        if(idx == -1)
            order.push_back(NULL);
        else
            order.push_back(m_curves->at(idx)->curve);
    }

    QString csv;
    QString lineEnd;
    switch(ui->endBox->currentIndex())
    {
        case 0: lineEnd = "\r\n"; break;
        case 1: lineEnd = "\n"; break;
        case 2: lineEnd = "\n\r"; break;
        case 3: lineEnd = "\r"; break;
    }

    if(ui->colNamesBox->isChecked())
    {
        for(quint32 i = 0; i < order.size(); ++i)
        {
            if(!order[i])
                csv += "\"index\"";
            else
                csv += "\"" + order[i]->title().text() + "\"";
            csv += ui->sepEdit->text();
        }
        csv += lineEnd;
    }

    for(quint32 line = start; line < end; ++line)
    {
        emit updateProgress((line - start)*100/(end - start));

        for(quint32 i = 0; i < order.size(); ++i)
        {
            if(!order[i])
                csv += QString::number(line);
            else
            {
                if(line >= order[i]->getSize())
                    csv += "-1";
                else
                    csv += QString::number(order[i]->sample(line).y());
            }
            csv += ui->sepEdit->text();
        }
        csv += lineEnd;
    }
    return csv;
}
示例#5
0
bool KviPackageWriter::packFile(KviFile * pFile, KviPackageWriterDataField * pDataField)
{
	QString szProgressText = QString(__tr2qs("Packaging file %1")).arg(pDataField->m_szFileLocalName);
	if(!updateProgress(m_p->iCurrentProgress, szProgressText))
		return false; // aborted

	KviFile source(pDataField->m_szFileLocalName);
	if(!source.open(QFile::ReadOnly))
	{
		setLastError(__tr2qs("Failed to open a source file for reading"));
		return false;
	}

	kvi_u32_t uSize = source.size();

// Flags
#ifdef COMPILE_ZLIB_SUPPORT
	kvi_u32_t uFlags = pDataField->m_bFileAllowCompression ? (uSize > 64 ? KVI_PACKAGE_DATAFIELD_FLAG_FILE_DEFLATE : 0)
	                                                       : 0;
#else
	kvi_u32_t uFlags = 0;
#endif

	if(!pFile->save(uFlags))
		return writeError();

	QByteArray szTargetFileName = pDataField->m_szFileTargetName.toUtf8();

	// Path
	if(!pFile->save(szTargetFileName))
		return writeError();

	kvi_file_offset_t savedSizeOffset = pFile->pos();

	// Size : will update it if compression is requested
	if(!pFile->save(uSize))
		return writeError();

	pDataField->m_uWrittenFieldLength = 4 + 4 + 4 + szTargetFileName.length(); // sizeof(flags + uncompressed size + path len + path)

// FilePayload
#ifdef COMPILE_ZLIB_SUPPORT
	if(uFlags & KVI_PACKAGE_DATAFIELD_FLAG_FILE_DEFLATE)
	{
		unsigned char ibuffer[BUFFER_SIZE];
		unsigned char obuffer[BUFFER_SIZE];

		kvi_i32_t iReaded = source.read((char *)ibuffer, BUFFER_SIZE);
		if(iReaded < 0)
			return readError();

		z_stream zstr;
		zstr.zalloc = Z_NULL;
		zstr.zfree = Z_NULL;
		zstr.opaque = Z_NULL;
		zstr.next_in = ibuffer;
		zstr.avail_in = iReaded;
		zstr.next_out = obuffer;
		zstr.avail_out = BUFFER_SIZE;

		if(deflateInit(&zstr, 9) != Z_OK)
		{
			setLastError(__tr2qs("Compression library initialization error"));
			return false;
		}

		while(iReaded > 0)
		{
			zstr.next_out = obuffer;
			zstr.avail_out = BUFFER_SIZE;

			if(deflate(&zstr, Z_NO_FLUSH) != Z_OK)
			{
				setLastError(__tr2qs("Compression library error"));
				return false;
			}

			if(zstr.avail_out < BUFFER_SIZE)
			{
				int iCompressed = zstr.next_out - obuffer;
				pDataField->m_uWrittenFieldLength += iCompressed;
				if(pFile->write((char *)obuffer, iCompressed) != iCompressed)
				{
					deflateEnd(&zstr);
					return writeError();
				}
			}

			if(zstr.avail_in < BUFFER_SIZE)
			{
				int iDataToRead = BUFFER_SIZE - zstr.avail_in;
				if(iDataToRead < BUFFER_SIZE)
				{
					if(ibuffer != zstr.next_in)
					{
						// hum, there is still some data in the buffer to be readed
						// and it is not at the beginning...move it to the beginning of ibuffer
						memmove(ibuffer, zstr.next_in, zstr.avail_in);
					}
				}
				iReaded = source.read((char *)(ibuffer + zstr.avail_in), iDataToRead);
				if(iReaded < 0)
				{
					deflateEnd(&zstr);
					return readError();
				}
				zstr.avail_in += iReaded;
				zstr.next_in = ibuffer;

				if((zstr.total_in % 2000000) == 0)
				{
					QString szTmp = QString(" (%1 of %2 bytes)").arg(zstr.total_in, uSize);
					QString szPrg = szProgressText + szTmp;
					if(!updateProgress(m_p->iCurrentProgress, szPrg))
						return false; // aborted
				}
			}
		}
		// flush pending output
		zstr.next_out = obuffer;
		zstr.avail_out = BUFFER_SIZE;

		int ret;
		do
		{
			ret = deflate(&zstr, Z_FINISH);

			if((ret == Z_OK) || (ret == Z_STREAM_END))
			{
				if(zstr.avail_out < BUFFER_SIZE)
				{
					int iCompressed = zstr.next_out - obuffer;
					pDataField->m_uWrittenFieldLength += iCompressed;
					if(pFile->write((char *)obuffer, iCompressed) != iCompressed)
					{
						deflateEnd(&zstr);
						return writeError();
					}
				}
				else
				{
					deflateEnd(&zstr);
					setLastError(__tr2qs("Compression library internal error"));
					return false;
				}

				zstr.next_out = obuffer;
				zstr.avail_out = BUFFER_SIZE;
			}

		} while(ret == Z_OK);

		// store the compressed data size
		kvi_file_offset_t here = pFile->pos();
		pFile->seek(savedSizeOffset);
		uSize = zstr.total_out;

		deflateEnd(&zstr);
		if(!pFile->save(uSize))
			return writeError();

		if(ret != Z_STREAM_END)
		{
			setLastError(__tr2qs("Error while compressing a file stream"));
			return false;
		}

		pFile->seek(here);
	}
	else
	{
#endif
		unsigned char buffer[BUFFER_SIZE];
		int iTotalFileSize = 0;
		kvi_i32_t iReaded = source.read((char *)buffer, BUFFER_SIZE);
		if(iReaded < 0)
			return readError();
		while(iReaded > 0)
		{
			iTotalFileSize += iReaded;
			if((iTotalFileSize % 1000000) == 0)
			{
				QString szTmp = QString(" (%1 of %2 bytes)").arg(iTotalFileSize, uSize);
				QString szPrg = szProgressText + szTmp;
				if(!updateProgress(m_p->iCurrentProgress, szPrg))
					return false; // aborted
			}
			pDataField->m_uWrittenFieldLength += iReaded;
			if(pFile->write((char *)buffer, iReaded) != iReaded)
				return writeError();
			iReaded = source.read((char *)buffer, BUFFER_SIZE);
		}
#ifdef COMPILE_ZLIB_SUPPORT
	}
#endif
	source.close();

	return true;
}
示例#6
0
 void ArtworkUploader::onUploadStarted() {
     LOG_DEBUG << "#";
     beginProcessing();
     m_Percent = 0;
     updateProgress();
 }
示例#7
0
void TDownlad::downloadProgress(int un,int deux)
{
    emit updateProgress(un, deux);
}
示例#8
0
文件: master.c 项目: geoffchu/chuffed
void Master::receiveReport() {
        int thread_no = s.MPI_SOURCE-1;

        MPI_Get_count(&s, MPI_INT, &message_length);
        message = (int*) malloc(message_length*sizeof(int));
        MPI_Recv(message, message_length, MPI_INT, s.MPI_SOURCE, REPORT_TAG, MPI_COMM_WORLD, &s);
        Report& r = *((Report*) message);

        //for (int i = 0; i < message_length; i++) fprintf(stderr, "%d ", message[i]); fprintf(stderr, "\n");

        if (PAR_DEBUG) fprintf(stderr, "Received report %d from %d\n", r.status, thread_no);

        if (r.status == RES_SEA) {
                if (wallClockTime() - last_send_learnts[thread_no] > min_share_time) sendLearnts(thread_no);
        }

        if (r.status != RES_SEA) {
                assert(job_start_time[thread_no] != NOT_WORKING);
                num_free_slaves++;
                job_start_time[thread_no] = NOT_WORKING;
                if (PAR_DEBUG) fprintf(stderr, "%d is free, %f\n", thread_no, wallClockTime());
        }
        
        if(slaveStates[thread_no] == NORMAL_SEARCH && r.status == RES_LUN){
          if(PAR_DEBUG) fprintf(stderr, "LUN: Slave %d solved cube of size %d\n", thread_no, cur_job[thread_no] ? cur_job[thread_no]->size : -1);
        }

        
        if (r.status == RES_GUN) { 
            if(PAR_DEBUG) fprintf(stderr, "Master: Received RES_GUN from %d\n", thread_no); 
            status = RES_GUN;
        }
        if (r.status == RES_SAT){
          if(PAR_DEBUG) fprintf(stderr, "Master: Received RES_SAT from %d\n", thread_no);
          status = RES_SAT;
        }
        

        if (r.status == RES_LUN && slaveStates[thread_no]==NORMAL_SEARCH && updateProgress(cur_job[thread_no]->size)) {
          if(so.greedyInit){
            
            assert(job_queue.size() == 0 && "size of job queue is strange? ");
            status = RES_GUN;
          }
          else{
                for (int i = 0; i < num_threads; i++) 
                  assert(job_start_time[i] == NOT_WORKING);
                assert(job_queue.size() == 0 && "Finished, but there are still jobs left?");
                status = RES_GUN;
          }
        }
        if(r.status == RES_GREEDY_DONE ){
          if(thread_no % 3 == 0){
            
          }
          else if(thread_no % 3 == 1){
            // Slave is waiting right now. So, set state here immediately!
            if(so.mixWS_Portfolio){
              slaveStates[thread_no] = PORTFOLIO_SEARCH;
              setState(thread_no, PORTFOLIO_SEARCH);
            }
            else{
              slaveStates[thread_no] = NORMAL_SEARCH;
              setState(thread_no, NORMAL_SEARCH);
            }
            slavesRunningGreedy--;
          }
          assert(so.greedyInit && "Slave returns GREEDY_DONE, but not in greedy-mode?");
          
        }

        if(r.status == RES_LUN && slaveStates[thread_no] == RUNNING_GREEDY){
          if(thread_no % 3 == 0){
            
          }
          else if(thread_no % 3 == 1){
            setState(thread_no, NORMAL_SEARCH);
            slaveStates[thread_no] = NORMAL_SEARCH;
          }
          else{
            setState(thread_no, NORMAL_SEARCH);
          }
        }
        if (num_free_slaves == num_threads && job_queue.size() == 0 && status != RES_GUN && !so.purePortfolio) {
                for (int i = 0; i < search_progress.size(); i++) printf("%d ", search_progress[i]);
                assert(false && "No free slave, and no RES_GUN! ");
        }

        if (status != RES_GUN || true) receiveLearnts(r, thread_no, message_length);
        free(message);

}
示例#9
0
RoutingWidget::RoutingWidget( MarbleWidget *marbleWidget, QWidget *parent ) :
    QWidget( parent ), d( new RoutingWidgetPrivate( marbleWidget ) )
{
    d->m_ui.setupUi( this );
    d->m_ui.routeComboBox->setVisible( false );
    d->m_ui.routeComboBox->setModel( d->m_routingManager->alternativeRoutesModel() );

    d->m_routingLayer->synchronizeAlternativeRoutesWith( d->m_ui.routeComboBox );

    d->m_ui.routingProfileComboBox->setModel( d->m_routingManager->profilesModel() );

    connect( d->m_routingManager->profilesModel(), SIGNAL( rowsInserted( QModelIndex, int, int ) ),
             this, SLOT( selectFirstProfile() ) );
    connect( d->m_routingManager->profilesModel(), SIGNAL( modelReset() ),
             this, SLOT( selectFirstProfile() ) );
    connect( d->m_routingLayer, SIGNAL( placemarkSelected( QModelIndex ) ),
             this, SLOT( activatePlacemark( QModelIndex ) ) );
    connect( d->m_routingLayer, SIGNAL( pointSelected( GeoDataCoordinates ) ),
             this, SLOT( retrieveSelectedPoint( GeoDataCoordinates ) ) );
    connect( d->m_routingLayer, SIGNAL( pointSelectionAborted() ),
             this, SLOT( pointSelectionCanceled() ) );
    connect( d->m_routingManager, SIGNAL( stateChanged( RoutingManager::State, RouteRequest* ) ),
             this, SLOT( updateRouteState( RoutingManager::State, RouteRequest* ) ) );
    connect( d->m_routingManager, SIGNAL( routeRetrieved( GeoDataDocument* ) ),
             this, SLOT( indicateRoutingFailure( GeoDataDocument* ) ) );
    connect( d->m_routeRequest, SIGNAL( positionAdded( int ) ),
             this, SLOT( insertInputWidget( int ) ) );
    connect( d->m_routeRequest, SIGNAL( positionRemoved( int ) ),
             this, SLOT( removeInputWidget( int ) ) );
    connect( d->m_routeRequest, SIGNAL( routingProfileChanged() ),
             this, SLOT( updateActiveRoutingProfile() ) );
    connect( &d->m_progressTimer, SIGNAL( timeout() ),
             this, SLOT( updateProgress() ) );
    connect( d->m_ui.routeComboBox, SIGNAL( currentIndexChanged( int ) ),
             this, SLOT( switchRoute( int ) ) );
    connect( d->m_ui.routingProfileComboBox, SIGNAL( currentIndexChanged( int ) ),
             this, SLOT( setRoutingProfile( int ) ) );
    connect( d->m_routingManager->alternativeRoutesModel(), SIGNAL( rowsInserted( QModelIndex, int, int ) ),
             this, SLOT( updateAlternativeRoutes() ) );

    d->m_ui.directionsListView->setModel( d->m_routingModel );

    QItemSelectionModel *selectionModel = d->m_ui.directionsListView->selectionModel();
    d->m_routingLayer->synchronizeWith( selectionModel );
    connect( d->m_ui.directionsListView, SIGNAL( activated ( QModelIndex ) ),
             this, SLOT( activateItem ( QModelIndex ) ) );

    connect( d->m_ui.searchButton, SIGNAL( clicked( ) ),
             this, SLOT( retrieveRoute () ) );
    connect( d->m_ui.showInstructionsButton, SIGNAL( clicked( bool ) ),
             this, SLOT( showDirections() ) );
    connect( d->m_ui.configureButton, SIGNAL( clicked() ),
             this, SLOT( configureProfile() ) );

    for( int i=0; i<d->m_routeRequest->size(); ++i ) {
        insertInputWidget( i );
    }

    for ( int i=0; i<2 && d->m_inputWidgets.size()<2; ++i ) {
        // Start with source and destination if the route is empty yet
        addInputWidget();
    }
    //d->m_ui.descriptionLabel->setVisible( false );
    d->m_ui.resultLabel->setVisible( false );
    setShowDirectionsButtonVisible( false );
    updateActiveRoutingProfile();

    if ( MarbleGlobal::getInstance()->profiles() & MarbleGlobal::SmallScreen ) {
        d->m_ui.directionsListView->setVisible( false );
#ifdef Q_WS_MAEMO_5
        d->m_ui.directionsListView->setAttribute( Qt::WA_Maemo5StackedWindow );
        d->m_ui.directionsListView->setWindowFlags( Qt::Window );
        d->m_ui.directionsListView->setWindowTitle( tr( "Directions - Marble" ) );
#endif // Q_WS_MAEMO_5
    }
}
示例#10
0
bool
MacroDevice::download( const QDir &tmpdir,
                         QList<DeviceDownloadFile> &files,
                         QString &err)
{
    if (MACRO_DEBUG) printf("download O-Synce Macro");

    if (!dev->open(err)) {
        err = tr("ERROR: open failed: ") + err;
        return false;
    }

    emit updateStatus(tr("Request number of training..."));
    if (MACRO_DEBUG) printf("Request number of training\n");

    MacroPacket cmd(NUMBER_OF_TRAINING_REQUESTS);
    cmd.addToPayload(UNKNOWN);

    if (!cmd.write(dev, err)) return false;

    if(m_Cancelled)
    {
        err = tr("download cancelled");
        return false;
    }

    MacroPacket response = MacroPacket();
    response.read(dev, 2, err);

    if (response.payload.size() == 0)
    {
        err = tr("no data");
        return false;
    }

    char count = response.payload.at(0);

    if (count == 0)
    {
        err = tr("no data");
        return false;
    }

    response.read(dev, 7*count, err);

    if (!response.verifyCheckSum(dev, err))
    {
        err = tr("data error");
        return false;
    }

    if(m_Cancelled)
    {
        err = tr("download cancelled");
        return false;
    }

    // create temporary file
    QString tmpl = tmpdir.absoluteFilePath(".macrodl.XXXXXX");
    QTemporaryFile tmp(tmpl);
    tmp.setAutoRemove(false);

    if (!tmp.open()) {
        err = tr("Failed to create temporary file ")
            + tmpl + ": " + tmp.error();
        return false;
    }

    if (MACRO_DEBUG) printf("Acknowledge");
    cmd= MacroPacket(ACKNOWLEDGE);
    cmd.addToPayload(response.command);
    if (!cmd.write(dev, err)) return false;

    // timestamp from the first training
    struct tm start;
    start.tm_sec = bcd2Int(response.payload.at(2));
    start.tm_min = bcd2Int(response.payload.at(3));
    start.tm_hour = bcd2Int(response.payload.at(4));
    start.tm_mday = bcd2Int(response.payload.at(5));
    start.tm_mon = hex2Int(response.payload.at(6)) -1;
    start.tm_year = bcd2Int(response.payload.at(7)) -100;
    start.tm_isdst = -1;

    DeviceDownloadFile file;
    file.extension = "osyn";
    file.name = tmp.fileName();
    file.startTime.setTime_t( mktime( &start ));
    files.append(file);

    QTextStream os(&tmp);
    os << hex;

    for (int i = 0; i < count; i++)
    {
        if (MACRO_DEBUG) printf("Request training %d\n",i);
        emit updateStatus( QString(tr("Request datas of training %1 / %2..."))
            .arg(i+1).arg((int)count) );

        if(m_Cancelled)
        {
            err = tr("download cancelled");
            return false;
        }

        cmd = MacroPacket(TRAINING_DETAIL_REQUEST);
        cmd.addToPayload(i);
        if (!cmd.write(dev, err)) return false;

        if(m_Cancelled)
        {
            err = tr("download cancelled");
            return false;
        }
        bool lastpage = false;
        while (!lastpage)
        {
            MacroPacket response2 = MacroPacket();
            response2.read(dev, 259, err);

            if (!response2.verifyCheckSum(dev, err))
            {
                err = tr("data error");
                return false;
            }

            if (hexHex2Int(response2.payload.at(0), response2.payload.at(1)) == LAST_PAGE)
                lastpage = true;

            //int training_flag = hex2Int(response2.payload.at(43));
            tmp.write(response2.dataArray());
            emit updateProgress( QString(tr("training %1/%2... (%3 Bytes)"))
                .arg(i+1)
                .arg((int)count)
                .arg(tmp.size()) );
            if(m_Cancelled)
            {
                err = tr("download cancelled");
                return false;
            }

            if (MACRO_DEBUG) printf("Acknowledge\n");

            cmd= MacroPacket(ACKNOWLEDGE);
            cmd.addToPayload(response2.command);
            if (!cmd.write(dev, err)) return false;
        }

     }


    tmp.close();

    dev->close();

    // QTemporaryFile initially has permissions set to 0600.
    // Make it readable by everyone.
    tmp.setPermissions(tmp.permissions()
                       | QFile::ReadOwner | QFile::ReadUser
                       | QFile::ReadGroup | QFile::ReadOther);


    return true;
}
示例#11
0
static void resetProgress()
{
    loadingProgressCounter = 0;
    updateProgress(loadingProgressCounter);
}
示例#12
0
void Dirs::setProgress()
{
    loadingProgressCounter++;
    updateProgress(loadingProgressCounter);
}
示例#13
0
void DownloadJob::emitUpdate(int value) {
  emit updateProgress(value);
}
示例#14
0
bool KviPackageReader::unpackFile(KviFile * pFile, const QString & szUnpackPath)
{
	// Flags
	kvi_u32_t uFlags;
	if(!pFile->load(uFlags))
		return readError();

#ifndef COMPILE_ZLIB_SUPPORT
	if(uFlags & KVI_PACKAGE_DATAFIELD_FLAG_FILE_DEFLATE)
	{
		setLastError(__tr2qs("The package contains compressed data but this executable does not support compression"));
		return false;
	}
#endif

	// Path
	QString szPath;
	if(!pFile->load(szPath))
		return readError();

	QString szFileName = szUnpackPath;
	KviQString::ensureLastCharIs(szFileName, QChar(KVI_PATH_SEPARATOR_CHAR));

	szFileName += szPath;

	// no attacks please :)
	szFileName.replace(QString("..\\"), QString(""));
	szFileName.replace(QString("../"), QString(""));

	KviFileUtils::adjustFilePath(szFileName);

	int idx = szFileName.lastIndexOf(QChar(KVI_PATH_SEPARATOR_CHAR));
	if(idx != -1)
	{
		QString szPrefixPath = szFileName.left(idx);
		if(!KviFileUtils::makeDir(szPrefixPath))
		{
			setLastError(__tr2qs("Failed to create the target directory"));
			return false;
		}
	}

	KviFile dest(szFileName);
	if(!dest.open(QFile::WriteOnly | QFile::Truncate))
	{
		setLastError(__tr2qs("Failed to open a source file for reading"));
		return false;
	}

	QString szProgressText = QString(__tr2qs("Unpacking file %1")).arg(szFileName);
	if(!updateProgress(pFile->pos(), szProgressText))
		return false; // aborted

	// Size
	kvi_u32_t uSize;
	if(!pFile->load(uSize))
		return readError();

// FilePayload
#ifdef COMPILE_ZLIB_SUPPORT
	if(uFlags & KVI_PACKAGE_DATAFIELD_FLAG_FILE_DEFLATE)
	{
		//qDebug ("loading compressed data");
		int iRemainingSize = uSize;
		unsigned char ibuffer[BUFFER_SIZE];
		unsigned char obuffer[BUFFER_SIZE];

		int iToRead = iRemainingSize;
		if(iToRead > BUFFER_SIZE)
			iToRead = BUFFER_SIZE;
		int iReaded = pFile->read((char *)ibuffer, iToRead);
		iRemainingSize -= iReaded;

		z_stream zstr;
		zstr.zalloc = Z_NULL;
		zstr.zfree = Z_NULL;
		zstr.opaque = Z_NULL;
		zstr.next_in = ibuffer;
		zstr.avail_in = iReaded;
		zstr.next_out = obuffer;
		zstr.avail_out = BUFFER_SIZE;

		if(inflateInit(&zstr) != Z_OK)
		{
			setLastError(__tr2qs("Compression library initialization error"));
			return false;
		}

		while((iReaded > 0) && (iRemainingSize > 0))
		{
			zstr.next_out = obuffer;
			zstr.avail_out = BUFFER_SIZE;

			if(inflate(&zstr, Z_NO_FLUSH) != Z_OK)
			{
				setLastError(__tr2qs("Compression library error"));
				return false;
			}

			if(zstr.avail_out < BUFFER_SIZE)
			{
				int iDecompressed = zstr.next_out - obuffer;
				if(dest.write((char *)obuffer, iDecompressed) != iDecompressed)
				{
					inflateEnd(&zstr);
					return writeError();
				}
			}

			if(zstr.avail_in < BUFFER_SIZE)
			{
				int iDataToRead = BUFFER_SIZE - zstr.avail_in;
				if(iDataToRead < BUFFER_SIZE)
				{
					if(ibuffer != zstr.next_in)
					{
						// hum, there is still some data in the buffer to be readed
						// and it is not at the beginning...move it to the beginning of ibuffer
						memmove(ibuffer, zstr.next_in, zstr.avail_in);
					}
				}

				if(iDataToRead > iRemainingSize)
					iDataToRead = iRemainingSize;

				iReaded = pFile->read((char *)(ibuffer + zstr.avail_in), iDataToRead);
				if(iReaded < 0)
				{
					inflateEnd(&zstr);
					return readError();
				}

				iRemainingSize -= iReaded;
				zstr.avail_in += iReaded;
				zstr.next_in = ibuffer;

				if((zstr.total_in % 2000000) == 0)
				{
					QString szTmp = QString(" (%1 of %2 bytes)").arg(zstr.total_in, uSize);
					QString szPrg = szProgressText + szTmp;
					if(!updateProgress(pFile->pos(), szPrg))
						return false; // aborted
				}
			}
		}
		// flush pending output
		zstr.next_out = obuffer;
		zstr.avail_out = BUFFER_SIZE;

		int ret;

		do
		{
			ret = inflate(&zstr, Z_FINISH);

			if((ret == Z_OK) || (ret == Z_STREAM_END) || (ret == Z_BUF_ERROR))
			{
				if(zstr.avail_out < BUFFER_SIZE)
				{
					int iDecompressed = zstr.next_out - obuffer;
					if(dest.write((char *)obuffer, iDecompressed) != iDecompressed)
					{
						inflateEnd(&zstr);
						return writeError();
					}
				}
				else
				{
					//THIS HAPPENS FOR ZERO SIZE FILES
					qDebug("Hum... internal, rEWq (ret = %d) (avail_out = %d)", ret, zstr.avail_out);

					inflateEnd(&zstr);
					setLastError(__tr2qs("Compression library internal error"));
					return false;
				}
				zstr.next_out = obuffer;
				zstr.avail_out = BUFFER_SIZE;
			}

		} while((ret == Z_OK) || (ret == Z_BUF_ERROR));

		inflateEnd(&zstr);

		if(ret != Z_STREAM_END)
		{
			setLastError(__tr2qs("Error in compressed file stream"));
			return false;
		}
	}
	else
	{
#endif
		//qDebug("Load uncompressed data");
		unsigned char buffer[BUFFER_SIZE];
		int iTotalFileSize = 0;
		int iRemainingData = uSize;
		int iToRead = iRemainingData;
		if(iToRead > BUFFER_SIZE)
			iToRead = BUFFER_SIZE;
		int iReaded = 1;
		//qDebug("iReaded %i and iToRead %i and index %i",iReaded,iToRead,pFile->pos());
		while((iReaded > 0) && (iToRead > 0))
		{
			iReaded = pFile->read((char *)buffer, iToRead);
			if(iReaded > 0)
			{
				iTotalFileSize += iReaded;
				iRemainingData -= iReaded;

				if((iTotalFileSize % 3000000) == 0)
				{
					QString szTmp = QString(" (%1 of %2 bytes)").arg(iTotalFileSize).arg(uSize);
					QString szPrg = szProgressText + szTmp;
					if(!updateProgress(pFile->pos(), szPrg))
						return false; // aborted
				}
				//qDebug("write file with size %i and name %s",iReaded,dest.fileName().toUtf8().data());
				if(dest.write((char *)buffer, iReaded) != iReaded)
					return writeError();
			}
			//qDebug("Remains %i", iRemainingData);
			iToRead = iRemainingData;
			if(iToRead > BUFFER_SIZE)
				iToRead = BUFFER_SIZE;
		}
//qDebug("finish to read %i and index %i",iReaded,pFile->pos());
#ifdef COMPILE_ZLIB_SUPPORT
	}
#endif
	dest.close();

	return true;
}
示例#15
0
bool
PowerTapDevice::download( const QDir &tmpdir,
                         QList<DeviceDownloadFile> &files,
                         QString &err)
{
    if (!dev->open(err)) {
        err = tr("ERROR: open failed: ") + err;
        return false;
    }
    // make several attempts at reading the version
    int attempts = 3;
    int veridx = -1;
    int version_len;
    char vbuf[256];
    QByteArray version;

    do {
	if (!doWrite(dev, 0x56, false, err)) // 'V'
	    return false;

    emit updateStatus( tr("Reading version...") );
    if(m_Cancelled) {
        err = tr("download cancelled");
	    return false;
	}

	version_len = readUntilNewline(dev, vbuf, sizeof(vbuf), err);
	if (version_len < 0) {
	    err = tr("Error reading version: ") + err;
	    return false;
	}
	if (PT_DEBUG) {
	    printf("read version \"%s\"\n",
		   cEscape(vbuf, version_len).toAscii().constData());
	}
	version = QByteArray(vbuf, version_len);

	// We expect the version string to be something like
	// "VER 02.21 PRO...", so if we see two V's, it's probably
	// because there's a hardware echo going on.
	veridx = version.indexOf("VER");

    } while ((--attempts > 0) && (veridx < 0));

    if (veridx < 0) {
	err = QString(tr("Unrecognized version \"%1\""))
	    .arg(cEscape(vbuf, version_len));
	return false;
    }
    bool hwecho = version.indexOf('V') < veridx;
    if (PT_DEBUG) printf("hwecho=%s\n", hwecho ? "true" : "false");

    emit updateStatus( tr("Reading header...") );
    if(m_Cancelled) {
        err = tr("download cancelled");
        return false;
    }

    if (!doWrite(dev, 0x44, hwecho, err)) // 'D'
        return false;
    unsigned char header[6];
    int header_len = dev->read(header, sizeof(header), err);
    if (header_len != 6) {
        if (header_len < 0)
            err = tr("ERROR: reading header: ") + err;
        else
            err = tr("ERROR: timeout reading header");
        return false;
    }
    if (PT_DEBUG) {
        printf("read header \"%s\"\n",
               cEscape((char*) header,
                       sizeof(header)).toAscii().constData());
    }
    QVector<unsigned char> records;
    for (size_t i = 0; i < sizeof(header); ++i)
        records.append(header[i]);

    emit updateStatus( tr("Reading ride data...") );
    if(m_Cancelled) {
        err = tr("download cancelled");
        return false;
    }
    double recIntSecs = 0.0;

    fflush(stdout);
    while (true) {
        if (PT_DEBUG) printf("reading block\n");
        unsigned char buf[256 * 6 + 1];
        int n = dev->read(buf, 2, err);
        if (n < 2) {
            if (n < 0)
                err = tr("ERROR: reading first two: ") + err;
            else
                err = tr("ERROR: timeout reading first two");
            return false;
        }
        if (PT_DEBUG) {
            printf("read 2 bytes: \"%s\"\n",
                   cEscape((char*) buf, 2).toAscii().constData());
        }
        if (hasNewline((char*) buf, 2))
            break;
        unsigned count = 2;
        while (count < sizeof(buf)) {
            n = dev->read(buf + count, sizeof(buf) - count, err);
            if (n < 0) {
                err = tr("ERROR: reading block: ") + err;
                return false;
            }
            if (n == 0) {
                err = tr("ERROR: timeout reading block");
                return false;
            }
            if (PT_DEBUG) {
                printf("read %d bytes: \"%s\"\n", n,
                       cEscape((char*) buf + count, n).toAscii().constData());
            }
            count += n;
        }
        unsigned csum = 0;
        for (int i = 0; i < ((int) sizeof(buf)) - 1; ++i)
            csum += buf[i];
        if ((csum % 256) != buf[sizeof(buf) - 1]) {
            err = tr("ERROR: bad checksum");
            return false;
        }
        if (PT_DEBUG) printf("good checksum\n");
        for (size_t i = 0; i < sizeof(buf) - 1; ++i)
            records.append(buf[i]);
        if (recIntSecs == 0.0) {
            unsigned char *data = records.data();
            bool bIsVer81 = PowerTapUtil::is_Ver81(data);
            for (int i = 0; i < records.size(); i += 6) {
                if (PowerTapUtil::is_config(data + i, bIsVer81)) {
                    unsigned unused1, unused2, unused3;
                    PowerTapUtil::unpack_config(
                        data + i, &unused1, &unused2,
                        &recIntSecs, &unused3, bIsVer81);
                }
            }
        }
        if (recIntSecs != 0.0) {
            int min = (int) round(records.size() / 6 * recIntSecs);
            emit updateProgress( QString(tr("progress: %1:%2"))
                .arg(min / 60)
                .arg(min % 60, 2, 10, QLatin1Char('0')));
        }
        if(m_Cancelled){
            err = tr("download cancelled");
            return false;
        }
        if (!doWrite(dev, 0x71, hwecho, err)) // 'q'
            return false;
    }

    QString tmpl = tmpdir.absoluteFilePath(".ptdl.XXXXXX");
    QTemporaryFile tmp(tmpl);
    tmp.setAutoRemove(false);
    if (!tmp.open()) {
        err = tr("Failed to create temporary file ")
            + tmpl + ": " + tmp.error();
        return false;
    }
    // QTemporaryFile initially has permissions set to 0600.
    // Make it readable by everyone.
    tmp.setPermissions(tmp.permissions()
                       | QFile::ReadOwner | QFile::ReadUser
                       | QFile::ReadGroup | QFile::ReadOther);

    DeviceDownloadFile file;
    file.extension = "raw";
    file.name = tmp.fileName();

    QTextStream os(&tmp);
    os << hex;
    os.setPadChar('0');

    bool time_set = false;
    unsigned char *data = records.data();
    bool bIsVer81 = PowerTapUtil::is_Ver81(data);

    for (int i = 0; i < records.size(); i += 6) {
        if (data[i] == 0 && !bIsVer81)
            continue;
        for (int j = 0; j < 6; ++j) {
            os.setFieldWidth(2);
            os << data[i+j];
            os.setFieldWidth(1);
            os << ((j == 5) ? "\n" : " ");
        }
        if (!time_set && PowerTapUtil::is_time(data + i, bIsVer81)) {
            struct tm time;
            time_t timet = PowerTapUtil::unpack_time(data + i, &time, bIsVer81);
            file.startTime.setTime_t( timet );
            time_set = true;
        }
    }
    if (!time_set) {
        err = tr("Failed to find ride time.");
        tmp.setAutoRemove(true);
        return false;
    }

    files << file;
    return true;
}
示例#16
0
void CompressTouche::compress_sound_data(Common::Filename *inpath, Common::Filename *outpath) {
	int i;
	uint32 current_offset;
	uint32 offsets_table[MAX_OFFSETS];

	Common::File output(*outpath, "wb");

	output.writeUint16LE(1); /* current version */
	output.writeUint16LE(0); /* flags */

	current_offset = HEADER_SIZE;

	/* write 0 offsets table */
	for (i = 0; i < MAX_OFFSETS; ++i) {
		offsets_table[i] = 0;
		output.writeUint32LE(offsets_table[i]);
		current_offset += 4;
	}

	/* process 'OBJ' file */
	inpath->setFullName("OBJ");
	Common::File input(*inpath, "rb");

	offsets_table[0] = current_offset;
	current_offset = compress_sound_data_file(current_offset, output, input, input_OBJ_offs, input_OBJ_size, OBJ_HDR_LEN);
	input.close();
	print("Processed '%s'.", inpath->getFullPath().c_str());

	/* process Vxx files */
	for (i = 1; i < MAX_OFFSETS; ++i) {
		updateProgress(i, MAX_OFFSETS);

		char d[16];
		sprintf(d, "V%d", i);
		inpath->setFullName(d);

		try {
			input.open(*inpath, "rb");
			offsets_table[i] = current_offset;
			current_offset = compress_sound_data_file(current_offset, output, input, input_Vxx_offs, input_Vxx_size, Vxx_HDR_LEN);
			input.close();
			print("Processed '%s'.", inpath->getFullPath().c_str());
		} catch (...) {
			//print("Skipping '%s'.", inpath->getFullPath().c_str());
		}
	}

	/* fix global offsets table at the beginning of the file */
	output.seek(HEADER_SIZE, SEEK_SET);
	for (i = 0; i < MAX_OFFSETS; ++i) {
		output.writeUint32LE(offsets_table[i]);
	}

	output.close();

	/* cleanup */
	Common::removeFile(TEMP_RAW);
	Common::removeFile(tempEncoded);

	print("Done.");
}
// ******************************************************************************************
// Save package using default path
// ******************************************************************************************
bool ConfigurationFilesWidget::generatePackage()
{
  // Get path name
  std::string new_package_path = stack_path_->getPath();

  // Check that a valid stack package name has been given
  if( new_package_path.empty() )
  {
    QMessageBox::warning( this, "Error Generating", "No package path provided. Please choose a directory location to generate the MoveIt configuration files." );
    return false;
  }

  // Check setup assist deps
  if( !checkDependencies() )
    return false; // canceled

  // Check that all groups have components
  if( !noGroupsEmpty() )
    return false; // not ready

  // Trim whitespace from user input
  boost::trim( new_package_path );

  // Get the package name ---------------------------------------------------------------------------------
  new_package_name_ = getPackageName( new_package_path );

  const std::string setup_assistant_file = config_data_->appendPaths( new_package_path, ".setup_assistant" );

  // Make sure old package is correct package type and verify over write
  if( fs::is_directory( new_package_path ) && !fs::is_empty( new_package_path ) )
  {

    // Check if the old package is a setup assistant package. If it is not, quit
    if( ! fs::is_regular_file( setup_assistant_file ) )
    {
      QMessageBox::warning( this, "Incorrect Folder/Package",
                            QString("The chosen package location already exists but was not previously created using this MoveIt Setup Assistant. If this is a mistake, replace the missing file: ")
                            .append( setup_assistant_file.c_str() ) );
      return false;
    }

    // Confirm overwrite
    if( QMessageBox::question( this, "Confirm Package Update",
                               QString("Are you sure you want to overwrite this existing package with updated configurations?<br /><i>")
                               .append( new_package_path.c_str() )
                               .append( "</i>" ),
                               QMessageBox::Ok | QMessageBox::Cancel)
        == QMessageBox::Cancel )
    {
      return false; // abort
    }

  }
  else // this is a new package (but maybe the folder already exists)
  {
    // Create new directory ------------------------------------------------------------------
    try
    {
      fs::create_directory( new_package_path ) && !fs::is_directory( new_package_path );
    }
    catch( ... )
    {
      QMessageBox::critical( this, "Error Generating Files",
                             QString("Unable to create directory ").append( new_package_path.c_str() ) );
      return false;
    }
  }

  // Begin to create files and folders ----------------------------------------------------------------------
  std::string absolute_path;

  for (int i = 0; i < gen_files_.size(); ++i)
  {
    GenerateFile* file = &gen_files_[i];

    // Check if we should skip this file
    if( !file->generate_ )
    {
      continue;
    }

    // Create the absolute path
    absolute_path = config_data_->appendPaths( new_package_path, file->rel_path_ );
    ROS_DEBUG_STREAM("Creating file " << absolute_path );

    // Run the generate function
    if( !file->gen_func_(absolute_path) )
    {
      // Error occured
      QMessageBox::critical( this, "Error Generating File",
                             QString("Failed to generate folder or file: '")
                             .append( file->rel_path_.c_str() ).append("' at location:\n").append( absolute_path.c_str() ));
      return false;
    }
    updateProgress(); // Increment and update GUI
  }

  return true;
}
示例#18
0
/*!
 * \brief IPProcessGrid::execute
 */
void IPProcessGrid::execute(bool forcedUpdate /* = false*/)
{
    // if no processes yet, then exit
    if(_scene->steps()->size() < 1)
    {
        return;
    }

    // if already running or nothing has changed, exit
    if(_isRunning || !_updateNeeded)
    {
        return;
    }
    // prevent user changes during execution
    _mainWindow->lockScene();
    _isRunning = true;
    _sequenceCount = 0;

    buildQueue();

    int totalDurationMs = 0;

    // execute the processes
    int counter = 0;
    int limit = 10000;

    QList<IPProcessStep*> afterProcessingList;

    QListIterator<IPProcessStep *> it(_processList);
    while (it.hasNext() && counter < limit)
    {
        if(_stopExecution)
            return;

        IPProcessStep* step = it.next();
        _currentStep = step;

        // make sure the progress bar gets filled
        updateProgress(1);

        // source processes don't have inputs
        if(step->process()->isSource())
        {
            // check if is sequence
            //IPLLoadImageSequence* sequenceProcess = dynamic_cast<IPLLoadImageSequence*>(step->process());

            // update if index has changed
            /*if(sequenceProcess && (_sequenceIndex != _lastSequenceIndex))
            {
                sequenceProcess->setSequenceIndex(_sequenceIndex);
                propagateNeedsUpdate(sequenceProcess);
            }*/

            // execute thread
            if(!step->process()->isResultReady() || forcedUpdate)
            {
                step->process()->resetMessages();
                step->process()->beforeProcessing();
                int durationMs = executeThread(step->process());
                //step->process()->afterProcessing();

                // afterProcessing will be called later
                afterProcessingList.append(step);

                totalDurationMs += durationMs;
                step->setDuration(durationMs);

                if(!step->process()->hasErrors())
                    step->updateThumbnail();

                // update error messages
                _mainWindow->updateProcessMessages();
            }

            /*if(sequenceProcess)
            {
                int currentSequenceCount = sequenceProcess->sequenceCount();
                _sequenceCount = std::max(_sequenceCount, currentSequenceCount);
                emit sequenceChanged(_sequenceIndex, _sequenceCount);
            }*/
        }
        else
        {
            if(!step->process()->isResultReady() || forcedUpdate)
            {
                // execute process once for every input
                for(int i=0; i < step->edgesIn()->size(); i++)
                {
                    IPProcessEdge* edge = step->edgesIn()->at(i);
                    int indexFrom = edge->indexFrom();
                    int indexTo = edge->indexTo();
                    IPProcessStep* stepFrom = edge->from();

                    IPLImage* result = static_cast<IPLImage*>(stepFrom->process()->getResultData(indexFrom));

                    // invalid result, stopp the execution
                    if(!result)
                    {
                        QString msg("Invalid operation at step: ");
                        msg.append(QString::fromStdString(stepFrom->process()->title()));
                        _mainWindow->showMessage(msg, MainWindow::MESSAGE_ERROR);
                        break;
                    }

                    // execute thread
                    step->process()->resetMessages();
                    step->process()->beforeProcessing();
                    int durationMs = executeThread(step->process(), result, indexTo, mainWindow()->useOpenCV());
                    //step->process()->afterProcessing();

                    // afterProcessing will be called later
                    afterProcessingList.append(step);

                    totalDurationMs += durationMs;
                    step->setDuration(durationMs);

                    step->updateThumbnail();

                    // update error messages
                    _mainWindow->updateProcessMessages();
                }
            }
        }

        // make sure the progress bar gets filled
        updateProgress(100);

        counter++;
    }

    if(_stopExecution)
        return;

    // update images
    _mainWindow->imageViewer()->updateImage();
    _mainWindow->imageViewer()->showProcessDuration(totalDurationMs);


    // update process graph
    _mainWindow->updateGraphicsView();
    _mainWindow->unlockScene();

    _isRunning = false;
    _currentStep = NULL;

    // if sequence, then run execute next step
    /*if(_sequenceCount > 0)
    {
        // notify GUI
        emit sequenceChanged(_sequenceIndex, _sequenceCount);

        if(_isSequenceRunning)
        {
            //setParamsHaveChanged();
            _mainWindow->execute(true);
        }
    }

    // find sequence processes
    //bool graphNeedsUpdate = false;
    for(auto it = _scene->steps()->begin(); it < _scene->steps()->end(); ++it)
    {
        IPProcessStep* step = (IPProcessStep*) *it;
        IPLProcess* process = step->process();

        if(process->isSequence())
        {
            process->requestUpdate();
            propertyChanged(process);
            requestUpdate();
        }
    }*/

    //if(_updateID > _currentUpdateID)
    //    _mainWindow->execute(false);

    // only for testing the camera
    //if(graphNeedsUpdate)
    //    _mainWindow->execute(false);

    _updateNeeded = false;

    // call afterProcessing of all steps which were executed this time
    // processes like the camera might request another execution
    QListIterator<IPProcessStep *> it2(_processList);
    while (it2.hasNext())
    {
        IPProcessStep* step = it2.next();
        step->process()->afterProcessing();
    }
}
bool QmlProfilerFileReader::loadQzt(QIODevice *device)
{
    QDataStream stream(device);
    stream.setVersion(QDataStream::Qt_5_5);

    QByteArray magic;
    stream >> magic;
    if (magic != QByteArray("QMLPROFILER")) {
        emit error(tr("Invalid magic: %1").arg(QLatin1String(magic)));
        return false;
    }

    qint32 dataStreamVersion;
    stream >> dataStreamVersion;

    if (dataStreamVersion > QDataStream::Qt_DefaultCompiledVersion) {
        emit error(tr("Unknown data stream version: %1").arg(dataStreamVersion));
        return false;
    }
    stream.setVersion(dataStreamVersion);

    stream >> m_traceStart >> m_traceEnd;

    QBuffer buffer;
    QDataStream bufferStream(&buffer);
    bufferStream.setVersion(dataStreamVersion);
    QByteArray data;
    updateProgress(device);

    stream >> data;
    buffer.setData(qUncompress(data));
    buffer.open(QIODevice::ReadOnly);
    bufferStream >> m_eventTypes;
    buffer.close();
    emit typesLoaded(m_eventTypes);
    updateProgress(device);

    stream >> data;
    buffer.setData(qUncompress(data));
    buffer.open(QIODevice::ReadOnly);
    bufferStream >> m_notes;
    buffer.close();
    emit notesLoaded(m_notes);
    updateProgress(device);

    const int eventBufferLength = 1024;
    QVector<QmlEvent> eventBuffer(eventBufferLength);
    int eventBufferIndex = 0;
    while (!stream.atEnd()) {
        stream >> data;
        buffer.setData(qUncompress(data));
        buffer.open(QIODevice::ReadOnly);
        while (!buffer.atEnd()) {
            if (isCanceled())
                return false;
            QmlEvent &event = eventBuffer[eventBufferIndex];
            bufferStream >> event;
            if (bufferStream.status() == QDataStream::Ok) {
                if (event.typeIndex() >= m_eventTypes.length()) {
                    emit error(tr("Invalid type index %1").arg(event.typeIndex()));
                    return false;
                }
                m_loadedFeatures |= (1ULL << m_eventTypes[event.typeIndex()].feature());
            } else if (bufferStream.status() == QDataStream::ReadPastEnd) {
                break; // Apparently EOF is a character so we end up here after the last event.
            } else if (bufferStream.status() == QDataStream::ReadCorruptData) {
                emit error(tr("Corrupt data before position %1.").arg(device->pos()));
                return false;
            } else {
                Q_UNREACHABLE();
            }
            if (++eventBufferIndex == eventBufferLength) {
                emit qmlEventsLoaded(eventBuffer);
                eventBufferIndex = 0;
            }
        }
        buffer.close();
        updateProgress(device);
    }
    eventBuffer.resize(eventBufferIndex);
    emit qmlEventsLoaded(eventBuffer);
    emit success();
    return true;
}
示例#20
0
bool KviPackageWriter::packInternal(const QString & szFileName, kvi_u32_t)
{

	KviFile f(szFileName);
	if(!f.open(QFile::WriteOnly | QFile::Truncate))
	{
		setLastError(__tr2qs("Can't open file for writing"));
		return false;
	}

	// write the PackageHeader
	// Magic
	char magic[4];
	magic[0] = 'K';
	magic[1] = 'V';
	magic[2] = 'P';
	magic[3] = 'F';
	if(f.write(magic, 4) != 4)
		return writeError();

	// Version
	kvi_u32_t uVersion = 0x1;
	if(!f.save(uVersion))
		return writeError();

	// Flags
	kvi_u32_t uFlags = 0x0;
	if(!f.save(uFlags))
		return writeError();

	// write PackageInfo
	// InfoFieldCount
	kvi_u32_t uCount = stringInfoFields()->count() + binaryInfoFields()->count();
	if(!f.save(uCount))
		return writeError();

	m_p->iCurrentProgress = 5;
	if(!updateProgress(m_p->iCurrentProgress, __tr2qs("Writing informational fields")))
		return false; // aborted

	// InfoFields (string)
	KviPointerHashTableIterator<QString, QString> it(*stringInfoFields());
	while(QString * s = it.current())
	{
		if(!f.save(it.currentKey()))
			return writeError();
		kvi_u32_t uType = KVI_PACKAGE_INFOFIELD_TYPE_STRING;
		if(!f.save(uType))
			return writeError();
		if(!f.save(*s))
			return writeError();
		++it;
	}

	// InfoFields (binary)
	KviPointerHashTableIterator<QString, QByteArray> it2(*binaryInfoFields());
	while(QByteArray * b = it2.current())
	{
		if(!f.save(it2.currentKey()))
			return writeError();
		kvi_u32_t uType = KVI_PACKAGE_INFOFIELD_TYPE_BINARYBUFFER;
		if(!f.save(uType))
			return writeError();
		if(!f.save(*b))
			return writeError();
		++it2;
	}

	m_p->iCurrentProgress = 10;
	if(!updateProgress(m_p->iCurrentProgress, __tr2qs("Writing package data")))
		return false; // aborted

	// write PackageData
	int iIdx = 0;
	for(KviPackageWriterDataField * pDataField = m_p->pDataFields->first(); pDataField; pDataField = m_p->pDataFields->next())
	{
		kvi_u32_t uKviPackageWriterDataFieldType = pDataField->m_uType;
		if(!f.save(uKviPackageWriterDataFieldType))
			return writeError();

		kvi_file_offset_t savedLenOffset = f.pos();
		// here we will store the length of the field once it's written
		if(!f.save(uKviPackageWriterDataFieldType))
			return writeError();

		m_p->iCurrentProgress = 10 + ((90 * iIdx) / m_p->pDataFields->count());

		switch(pDataField->m_uType)
		{
			case KVI_PACKAGE_DATAFIELD_TYPE_FILE:
				if(!packFile(&f, pDataField))
					return false;
				break;
			default:
				setLastError(__tr2qs("Internal error"));
				return false;
				break;
		}

		kvi_file_offset_t savedEndOffset = f.pos();
		f.seek(savedLenOffset);
		if(!f.save(pDataField->m_uWrittenFieldLength))
			return writeError();

		f.seek(savedEndOffset);
		iIdx++;
	}

	return true;
}
示例#21
0
QByteArray GraphExport::generateBin()
{
    GraphCurve *c = m_curves->at(ui->curveBox->itemData(ui->curveBox->currentIndex()).toInt())->curve;
    Q_ASSERT(c);

    QByteArray bin;
    QBuffer buff(&bin);
    buff.open(QIODevice::WriteOnly);

    bool big = !ui->endianBox->currentIndex();
    int idxW = (1 << ui->idxWidthBox->currentIndex());

    const quint32 start = ui->sampleStartBox->value();
    const quint32 end = ui->sampleEndBox->value();

    for(quint32 i = start; i < end && i < c->getSize(); ++i)
    {
        emit updateProgress((i - start )*100/(end - start));

        if(ui->indexBox->isChecked())
        {
            quint64 idx = i;
            Utils::swapEndian(idx);
            if(!big)
                Utils::swapEndian(((char*)&idx)+(sizeof(idx)-idxW), idxW);
            buff.write(((char*)&idx)+(sizeof(idx)-idxW), idxW);
        }

        qreal s = c->sample(i).y();
        switch(c->getDataType())
        {
            case NUM_FLOAT:
            {
                float f = s;
                buff.write((char*)&f, sizeof(f));
                break;
            }
            case NUM_DOUBLE:
                buff.write((char*)&s, sizeof(s));
                break;
            default:
            {
                QVariant var(s);
                switch(c->getDataType())
                {
                    case NUM_UINT8:
                    case NUM_INT8:
                    {
                        quint8 y = var.toInt();
                        if(big) Utils::swapEndian((char*)&y, sizeof(y));
                        buff.write((char*)&y, sizeof(y));
                        break;
                    }
                    case NUM_UINT16:
                    case NUM_INT16:
                    {
                        quint16 y = var.toInt();
                        if(big) Utils::swapEndian((char*)&y, sizeof(y));
                        buff.write((char*)&y, sizeof(y));
                        break;
                    }
                    case NUM_UINT32:
                    case NUM_INT32:
                    {
                        quint32 y = var.toInt();
                        if(big) Utils::swapEndian((char*)&y, sizeof(y));
                        buff.write((char*)&y, sizeof(y));
                        break;
                    }
                    case NUM_UINT64:
                    case NUM_INT64:
                    {
                        quint64 y = var.toLongLong();
                        if(big) Utils::swapEndian((char*)&y, sizeof(y));
                        buff.write((char*)&y, sizeof(y));
                        break;
                    }
                }
                break;
            }
        }
    }
    buff.close();
    return bin;
}
示例#22
0
AudioRecorder::AudioRecorder()
{
//! [create-objs-1]
    audiosource = new QAudioCaptureSource;
    capture = new QMediaRecorder(audiosource);
//! [create-objs-1]

    // set a default file
    capture->setOutputLocation(QUrl("test.raw"));

    QWidget *window = new QWidget;
    QGridLayout* layout = new QGridLayout;

    QLabel* deviceLabel = new QLabel;
    deviceLabel->setText("Devices");
    deviceBox = new QComboBox(this);
    deviceBox->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Fixed);

    QLabel* codecLabel = new QLabel;
    codecLabel->setText("Codecs");
    codecsBox = new QComboBox(this);
    codecsBox->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Fixed);

    QLabel* qualityLabel = new QLabel;
    qualityLabel->setText("Quality");
    qualityBox = new QComboBox(this);
    qualityBox->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Fixed);

//! [device-list]
    for(int i = 0; i < audiosource->deviceCount(); i++)
        deviceBox->addItem(audiosource->name(i));
//! [device-list]

//! [codec-list]
    QStringList codecs = capture->supportedAudioCodecs();
    for(int i = 0; i < codecs.count(); i++)
        codecsBox->addItem(codecs.at(i));
//! [codec-list]

    qualityBox->addItem("Low");
    qualityBox->addItem("Medium");
    qualityBox->addItem("High");

    connect(capture, SIGNAL(durationChanged(qint64)), this, SLOT(updateProgress(qint64)));
    connect(capture, SIGNAL(stateChanged(QMediaRecorder::State)), this, SLOT(stateChanged(QMediaRecorder::State)));

    layout->addWidget(deviceLabel,0,0,Qt::AlignHCenter);
    connect(deviceBox,SIGNAL(activated(int)),SLOT(deviceChanged(int)));
    layout->addWidget(deviceBox,0,1,1,3,Qt::AlignLeft);

    layout->addWidget(codecLabel,1,0,Qt::AlignHCenter);
    connect(codecsBox,SIGNAL(activated(int)),SLOT(codecChanged(int)));
    layout->addWidget(codecsBox,1,1,Qt::AlignLeft);

    layout->addWidget(qualityLabel,1,2,Qt::AlignHCenter);
    connect(qualityBox,SIGNAL(activated(int)),SLOT(qualityChanged(int)));
    layout->addWidget(qualityBox,1,3,Qt::AlignLeft);

    fileButton = new QPushButton(this);
    fileButton->setText(tr("Output File"));
    connect(fileButton,SIGNAL(clicked()),SLOT(selectOutputFile()));
    layout->addWidget(fileButton,3,0,Qt::AlignHCenter);

    button = new QPushButton(this);
    button->setText(tr("Record"));
    connect(button,SIGNAL(clicked()),SLOT(toggleRecord()));
    layout->addWidget(button,3,3,Qt::AlignHCenter);

    recTime = new QLabel;
    recTime->setText("0 sec");
    layout->addWidget(recTime,4,0,Qt::AlignHCenter);

    window->setLayout(layout);
    setCentralWidget(window);
    window->show();

    active = false;
}
示例#23
0
void CompressionExample::execute() {
	// By now, all arguments have been parsed, all members setup and all input paths setup
	// If this was a compression tool _format would contain the selected audio format
	// Note that we almost need no error handling, since exceptions will be thrown if we do
	// something bad, and all parameters have already been setup

	// This 'tool' doesn't takes two input files
	// It writes the of each file 100 times into X files, where X is the input file size.

	// _inputPaths[0].path is always valid and contains the correct path, same for 1
	Common::Filename inpath1(_inputPaths[0].path);
	Common::Filename inpath2(_inputPaths[1].path);

	// We always need to setup default output path, since there is no obligation to specify it
	// If you don't do this, the OS will usually default to the working directory, if we output a file
	// it will fail most likely
	if (_outputPath.empty())
		_outputPath = "output/";

	// The File class is very similar to the FILE struct, look in util.h for details
	File in1(inpath1, "r");
	File in2(inpath2, "r");

	// Read the complete contents of the files (if they don't contain NUL ofcourse)
	std::string text1 = in1.readString();
	std::string text2 = in2.readString();

	// Start the 'extraction'
	size_t total_files = in1.size() + in2.size();

	// There has to be some roof on this
	if (total_files > 1000)
		throw ToolException("Input files are too large!");

	for (size_t i = 0; i < total_files; ++i) {
		// This updates any progress bar, if there is any
		// if you don't support progress bars, you should use notifyProgress instead
		// to make sure progress can be aborted (print calls notifyProgress internally)
		updateProgress(i, total_files);

		// Convert i to string
		std::ostringstream outname;
		outname << i;

		// Open a file for writing
		if (_outputFiles) {
			File out(_outputPath.getPath() + outname.str() + ".exo", "w");

			// What we actually do, output some text alot
			for (size_t j = 0; j < 100; ++j) {
				if (i < in1.size())
					out.write(text1.c_str(), 1, text1.size());
				else
					out.write(text2.c_str(), 1, text2.size());
			}
		} else {
			// Do nothing for awhile
			for (int i = 0; i < 1000000; ++i) {
				int *n = new int;
				delete n;
			}
		}

		// Print can also throw an AbortException
		// Do NOT use printf or anything else that outputs to standard output, as it will not display in the GUI.
		print("Outputted file %d of %d\n", i, total_files);
	}

	// We indicate success by not throwing any exceptions during the execution
	print("Extraction finished without errors!");
}