コード例 #1
0
void ExecuterProgressWatcher::onStepFinished()
{
    lastProgress = 1;
    emit progressChanged();
}
コード例 #2
0
ファイル: effect.cpp プロジェクト: Omega9/synthclone
void
Effect::process(const synthclone::Zone &/*zone*/,
                synthclone::SampleInputStream &inputStream,
                synthclone::SampleOutputStream &outputStream)
{
    synthclone::SampleFrameCount frames = inputStream.getFrames();
    float sampleRate = static_cast<float>(inputStream.getSampleRate());
    synthclone::SampleFrameCount fadeInFrames = fadeInEnabled ?
        static_cast<synthclone::SampleFrameCount>(fadeInTime * sampleRate) : 0;
    synthclone::SampleFrameCount fadeOutFrames = fadeOutEnabled ?
        static_cast<synthclone::SampleFrameCount>(fadeOutTime * sampleRate) : 0;
    synthclone::SampleFrameCount totalFadeFrames = fadeInFrames + fadeOutFrames;

    qDebug() << "\tfade in frames:" << fadeInFrames;
    qDebug() << "\t fade out frames:" << fadeOutFrames;

    // If the amount of frames spent fading is greater than the number of total
    // frames, then shorten the fades proportionally.  If anyone has a better
    // suggestion, I'm all ears.
    if (totalFadeFrames > frames) {

        qDebug() << "adjusting fade frames";

        fadeInFrames = static_cast<synthclone::SampleFrameCount>
            (static_cast<float>(fadeInFrames) *
             (static_cast<float>(frames) /
              static_cast<float>(totalFadeFrames)));
        fadeOutFrames = frames - fadeInFrames;

        qDebug() << "\tfade in frames:" << fadeInFrames;
        qDebug() << "\t fade out frames:" << fadeOutFrames;

    }

    synthclone::SampleChannelCount channels = inputStream.getChannels();
    QScopedArrayPointer<float> audioDataPtr(new float[channels]);
    float *audioData = audioDataPtr.data();
    synthclone::SampleFrameCount currentFrame = 0;
    synthclone::SampleFrameCount framesRead;
    float volume;
    if (fadeInFrames) {

        qDebug() << "\tapplying fade in ...";

        emit statusChanged(tr("Creating fade-in of sample ..."));
        for (; currentFrame < fadeInFrames; currentFrame++) {
            framesRead = inputStream.read(audioData, 1);
            assert(framesRead == 1);
            volume = getAmplitude(fadeInStartVolume *
                                  (1.0 - (static_cast<float>(currentFrame + 1) /
                                          static_cast<float>(fadeInFrames))));
            for (int i = 0; i < channels; i++) {
                audioData[i] *= volume;
            }
            outputStream.write(audioData, 1);
            emit progressChanged(static_cast<float>(currentFrame + 1) /
                                 static_cast<float>(frames));
        }
    }
    synthclone::SampleFrameCount fadeOutStartFrame = frames - fadeOutFrames;
    synthclone::SampleFrameCount copyFrames = fadeOutStartFrame - currentFrame;

    qDebug() << "\tcopy frames:" << copyFrames;
    qDebug() << "\tfade out start frame:" << fadeOutStartFrame;

    if (copyFrames) {

        qDebug() << "copying frames ...";

        emit statusChanged(tr("Writing sample ..."));
        copyStartFrame = currentFrame;
        copyTotalFrames = frames;
        synthclone::SampleCopier copier;
        connect(&copier,
                SIGNAL(copyProgress(synthclone::SampleFrameCount,
                                    synthclone::SampleFrameCount)),
                SLOT(handleCopyProgress(synthclone::SampleFrameCount,
                                        synthclone::SampleFrameCount)),
                Qt::DirectConnection);
        copier.copy(inputStream, outputStream, copyFrames);
    }
    currentFrame += copyFrames;
    if (fadeOutFrames) {

        qDebug() << "\tapplying fade out ...";

        emit statusChanged(tr("Creating fade-out of sample ..."));
        for (; currentFrame < frames; currentFrame++) {
            framesRead = inputStream.read(audioData, 1);
            assert(framesRead == 1);
            volume = getAmplitude(fadeOutEndVolume *
                                  (static_cast<float>(currentFrame + 1 -
                                                      fadeOutStartFrame) /
                                   static_cast<float>(fadeOutFrames)));
            for (int i = 0; i < channels; i++) {
                audioData[i] *= volume;
            }
            outputStream.write(audioData, 1);
            emit progressChanged(static_cast<float>(currentFrame + 1) /
                                 static_cast<float>(frames));
        }
    }
    emit progressChanged(0.0);
    emit statusChanged("");

    qDebug() << "/Effect::process";

}
コード例 #3
0
void QDeclarativeAnimatedImage::load()
{
    Q_D(QDeclarativeAnimatedImage);

    QDeclarativeImageBase::Status oldStatus = d->status;
    qreal oldProgress = d->progress;

    if (d->url.isEmpty()) {
        delete d->_movie;
        d->setPixmap(QPixmap());
        d->progress = 0;
        d->status = Null;
        if (d->status != oldStatus)
            emit statusChanged(d->status);
        if (d->progress != oldProgress)
            emit progressChanged(d->progress);
    } else {
#ifndef QT_NO_LOCALFILE_OPTIMIZED_QML
        QString lf = QDeclarativeEnginePrivate::urlToLocalFileOrQrc(d->url);
        if (!lf.isEmpty()) {
            //### should be unified with movieRequestFinished
            d->_movie = new QMovie(lf);
            if (!d->_movie->isValid()){
                qmlInfo(this) << "Error Reading Animated Image File " << d->url.toString();
                delete d->_movie;
                d->_movie = 0;
                d->status = Error;
                if (d->status != oldStatus)
                    emit statusChanged(d->status);
                return;
            }
            connect(d->_movie, SIGNAL(stateChanged(QMovie::MovieState)),
                    this, SLOT(playingStatusChanged()));
            connect(d->_movie, SIGNAL(frameChanged(int)),
                    this, SLOT(movieUpdate()));
            d->_movie->setCacheMode(QMovie::CacheAll);
            if(d->playing)
                d->_movie->start();
            else
                d->_movie->jumpToFrame(0);
            if(d->paused)
                d->_movie->setPaused(true);
            d->setPixmap(d->_movie->currentPixmap());
            d->status = Ready;
            d->progress = 1.0;
            if (d->status != oldStatus)
                emit statusChanged(d->status);
            if (d->progress != oldProgress)
                emit progressChanged(d->progress);
            return;
        }
#endif
        d->status = Loading;
        d->progress = 0;
        emit statusChanged(d->status);
        emit progressChanged(d->progress);
        QNetworkRequest req(d->url);
        req.setAttribute(QNetworkRequest::HttpPipeliningAllowedAttribute, true);
        d->reply = qmlEngine(this)->networkAccessManager()->get(req);
        QObject::connect(d->reply, SIGNAL(finished()),
                         this, SLOT(movieRequestFinished()));
        QObject::connect(d->reply, SIGNAL(downloadProgress(qint64,qint64)),
                         this, SLOT(requestProgress(qint64,qint64)));
    }
コード例 #4
0
ファイル: SiteResponseModel.cpp プロジェクト: arkottke/strata
void SiteResponseModel::run()
{
    m_okToContinue = true;
    setHasResults(false);

    // Check the input -- FIMXE add more thorough checks
    if (m_siteProfile->rowCount() < 2) {
        qCritical() << "Need at least one soil layer!";
        m_okToContinue = false;
    }

    if (!m_motionLibrary->rowCount()) {
        qCritical() << "Need at least one input motion!";
        m_okToContinue = false;
    }

    if (!m_okToContinue)
        return;

    m_outputCatalog->clear();
    m_outputCatalog->log()->append(tr("<b>Starting Strata Calculation</b>"));

    // Determine the number of sites to be used in the computation
    const int siteCount = m_siteProfile->isVaried() ? m_siteProfile->profileCount() : 1;

    // Initialize the random number generator
    m_randNumGen->init();

    // Initialize the output
    m_outputCatalog->initialize(siteCount, m_motionLibrary);

    // Setup the progress bar with the number of steps
    const int motionCount = m_motionLibrary->motionCount();
    const int totalCount = motionCount * siteCount;
    emit progressRangeChanged(0, totalCount);
    emit progressChanged(0);

    m_outputCatalog->log()->append(tr("%1 Trial(s) (%2 Site(s) and %3 Motion(s) )")
                                   .arg(totalCount)
                                   .arg(siteCount)
                                   .arg(motionCount));

    int count = 0;
    for (int i = 0; i < siteCount; ++i) {
        // Break if not okay to continue
        if ( !m_okToContinue )
            break;

        m_outputCatalog->log()->append((
                                           QString(tr("[%1 of %2] Generating site and soil properties")).arg(i+1).arg(siteCount)));

        // Create the sublayers -- this randomizes the properties
        m_siteProfile->createSubLayers(m_outputCatalog->log());

        // FIXME -- check the site profile to ensure that the waves can be
        // computed for the intial coniditions
        int motionCountOffset = 0;
        for (int j = 0; j < m_motionLibrary->rowCount(); ++j ) {
            if (!m_motionLibrary->motionAt(j)->enabled()) {
                // Skip the disabled motion
                ++motionCountOffset;
                continue;
            }

            if (!m_okToContinue)
                // Break if not okay to continue
                break;

            // Output status
            m_outputCatalog->log()->append(QString(tr("\t[%1 of %2] Computing site response for motion: %3"))
                                           .arg(j - motionCountOffset + 1)
                                           .arg(motionCount)
                                           .arg(m_motionLibrary->motionAt(j)->name()));

            // Compute the site response
            if (!m_calculator->run(m_motionLibrary->motionAt(j), m_siteProfile) && m_okToContinue) {
                m_outputCatalog->log()->append(tr("\tWave propagation error -- removing site."));
                // Error in the calculation -- need to remove the site
                m_outputCatalog->removeLastSite();
                // Reset site count
                --i;
                break;
            }

            if (!m_okToContinue)
                // Break if not okay to continue
                break;

            // Generate the output
            m_outputCatalog->saveResults(j - motionCountOffset, m_calculator);

            // Increment the progress bar
            ++count;
            emit progressChanged(count);

            // Reset the sublayers
            m_siteProfile->resetSubLayers();
        }
    }

    if (m_okToContinue) {
        // Compute the statistics of the output
        m_outputCatalog->log()->append(tr("Computing statistics."));
        m_outputCatalog->finalize();
        setHasResults(true);
    } else {
        m_outputCatalog->log()->append(tr("<b>Canceled by the user.</b>"));
        setHasResults(false);
    }
}
コード例 #5
0
void BelowsPrg::slotSetProgress(int n)
{
    m_nProgress = n > m_nMaxProgressValue ? m_nMaxProgressValue : n < 0 ? 0 : n;
    repaint();
    emit progressChanged(m_nProgress);
}
コード例 #6
0
void MeterPrivate::setMeterValue(int value)
{
    progressChanged(value);
}
コード例 #7
0
void QDeclarativeBorderImage::load()
{
    Q_D(QDeclarativeBorderImage);
    if (d->progress != 0.0) {
        d->progress = 0.0;
        emit progressChanged(d->progress);
    }

    if (d->url.isEmpty()) {
        d->pix.clear(this);
        d->status = Null;
        setImplicitWidth(0);
        setImplicitHeight(0);
        emit statusChanged(d->status);
        update();
    } else {
        d->status = Loading;
        if (d->url.path().endsWith(QLatin1String("sci"))) {
#ifndef QT_NO_LOCALFILE_OPTIMIZED_QML
            QString lf = QDeclarativeEnginePrivate::urlToLocalFileOrQrc(d->url);
            if (!lf.isEmpty()) {
                QFile file(lf);
                file.open(QIODevice::ReadOnly);
                setGridScaledImage(QDeclarativeGridScaledImage(&file));
            } else
#endif
            {
                QNetworkRequest req(d->url);
                d->sciReply = qmlEngine(this)->networkAccessManager()->get(req);

                static int sciReplyFinished = -1;
                static int thisSciRequestFinished = -1;
                if (sciReplyFinished == -1) {
                    sciReplyFinished =
                        QNetworkReply::staticMetaObject.indexOfSignal("finished()");
                    thisSciRequestFinished =
                        QDeclarativeBorderImage::staticMetaObject.indexOfSlot("sciRequestFinished()");
                }

                QMetaObject::connect(d->sciReply, sciReplyFinished, this,
                                     thisSciRequestFinished, Qt::DirectConnection);
            }
        } else {

            QDeclarativePixmap::Options options;
            if (d->async)
                options |= QDeclarativePixmap::Asynchronous;
            if (d->cache)
                options |= QDeclarativePixmap::Cache;
            d->pix.clear(this);
            d->pix.load(qmlEngine(this), d->url, options);

            if (d->pix.isLoading()) {
                d->pix.connectFinished(this, SLOT(requestFinished()));
                d->pix.connectDownloadProgress(this, SLOT(requestProgress(qint64,qint64)));
            } else {
                QSize impsize = d->pix.implicitSize();
                setImplicitWidth(impsize.width());
                setImplicitHeight(impsize.height());

                if (d->pix.isReady()) {
                    d->status = Ready;
                } else {
                    d->status = Error;
                    qmlInfo(this) << d->pix.error();
                }

                d->progress = 1.0;
                emit statusChanged(d->status);
                emit progressChanged(d->progress);
                requestFinished();
                update();
            }
        }
    }

    emit statusChanged(d->status);
}
コード例 #8
0
void FileTransfer::updateProgress(qint64 transferred, qint64 total)
{
    m_progress = ((float)transferred)/((float)total);
    emit progressChanged();
}
コード例 #9
0
ファイル: transfer.cpp プロジェクト: marxoft/musikloud2
void Transfer::setProgress(int p) {
    if (p != progress()) {
        m_progress = p;
        emit progressChanged();
    }
}
コード例 #10
0
ファイル: QueryModel.cpp プロジェクト: evdmade01/dact
void QueryModel::updateProgress()
{
    emit progressChanged(d_entryIterator.progress());
}
コード例 #11
0
void
Downloader::report()
{
    emit statusChanged();
    emit progressChanged();
}
コード例 #12
0
ファイル: volume.cpp プロジェクト: beyondwolfeagle/drishti
void
Volume::findConnectedRegion(int mind, int maxd,
			    int minw, int maxw,
			    int minh, int maxh,
			    QList<int> pos,
			    bool sliceOnly)
{
  m_connectedbitmask.fill(false);

  uchar *lut = Global::lut();
  QStack<int> stack;

  uchar *vslice;
  uchar v0, g0;
  int d = pos[0];
  int w = pos[1];
  int h = pos[2];
  vslice = m_pvlFileManager.rawValue(d, w, h);
  v0 = vslice[0];
//  vslice = m_gradFileManager.rawValue(d, w, h);
//  g0 = vslice[0];
  g0 = 0;


  // put the seeds in
  for(int pi=0; pi<pos.size()/3; pi++)
    {
      int d = pos[3*pi];
      int w = pos[3*pi+1];
      int h = pos[3*pi+2];
      if (d >= mind && d <= maxd &&
	  w >= minw && w <= maxw &&
	  h >= minh && h <= maxh)
	{
	  qint64 idx = d*m_width*m_height + w*m_height + h;
	  if (m_bitmask.testBit(idx))
	    {
	      m_connectedbitmask.setBit(idx);
	      stack.push(d);
	      stack.push(w);
	      stack.push(h);
	    }
	}
    }

  if (sliceOnly)
    stack.clear();

  int pv = 0;
  int progv = 0;
  while(!stack.isEmpty())
    {
      progv++;
      if (progv == 1000)
	{
	  progv = 0;
	  pv = (++pv % 100);
	  emit progressChanged(pv);	  
	}

      int h = stack.pop();
      int w = stack.pop();
      int d = stack.pop();
      qint64 idx = d*m_width*m_height + w*m_height + h;
      if (m_bitmask.testBit(idx))
	{
	  int d0 = qMax(d-1, 0);
	  int d1 = qMin(d+1, m_depth-1);
	  int w0 = qMax(w-1, 0);
	  int w1 = qMin(w+1, m_width-1);
	  int h0 = qMax(h-1, 0);
	  int h1 = qMin(h+1, m_height-1);
	      
	  for(int d2=d0; d2<=d1; d2++)
	    for(int w2=w0; w2<=w1; w2++)
	      for(int h2=h0; h2<=h1; h2++)
		{
		  if (d2 >= mind && d2 <= maxd &&
		      w2 >= minw && w2 <= maxw &&
		      h2 >= minh && h2 <= maxh)
		    {
		      qint64 idx = d2*m_width*m_height +
			           w2*m_height + h2;
		      if ( m_bitmask.testBit(idx) &&
			   !m_connectedbitmask.testBit(idx) )
			{
//			  uchar v, g;
//			  vslice = m_pvlFileManager.rawValue(d2, w2, h2);
//			  v = vslice[0];
//			  vslice = m_gradFileManager.rawValue(d2, w2, h2);
//			  g = vslice[0];
//
//			  if (qAbs(v-v0) < Global::deltaV() &&
//			      g < Global::deltaG())
			    {
			      m_connectedbitmask.setBit(idx);
			      stack.push(d2);
			      stack.push(w2);
			      stack.push(h2);
			    }
			}
		    }
		}
	}
    } // end find connected
  //------------------------------------------------------

  emit progressReset();
}
コード例 #13
0
ファイル: backupinfo.cpp プロジェクト: LillyFoxBlogs/Sachesi
void BackupInfo::setProgress(const int &progress) {
    _progress = progress;
    emit progressChanged();
}
コード例 #14
0
ファイル: Load.cpp プロジェクト: FantasyNJ/BiliLocal-OSX
Load::Load(QObject *parent) : QObject(parent), d_ptr(new LoadPrivate(this))
{
	Q_D(Load);
	ins = this;
	setObjectName("Load");

	auto avProcess = [this](QNetworkReply *reply){
		Q_D(Load);
		Task &task = d->queue.head();
		int sharp = task.code.indexOf(QRegularExpression("[#_]"));
		switch (task.state){
		case None:
		{
			QString i = task.code.mid(2, sharp - 2);
			QString p = sharp == -1 ? QString() : task.code.mid(sharp + 1);
			QString url("http://www.%1/video/av%2/");
			url = url.arg(Utils::customUrl(Utils::Bilibili)).arg(i);
			if (!p.isEmpty()){
				url += QString("index_%1.html").arg(p);
			}
			forward(QNetworkRequest(url), Page);
			break;
		}
		case Page:
		{
			d->model->clear();
			QString api, id, video(reply->readAll());
			int part = video.indexOf("<select");
			if (part != -1 && sharp == -1){
				QRegularExpression r("(?<=>).*?(?=</option>)");
				QStringRef list(&video, part, video.indexOf("</select>", part) - part);
				QRegularExpressionMatchIterator i = r.globalMatch(list);
				api = "http://www.%1/video/%2/index_%3.html";
				api = api.arg(Utils::customUrl(Utils::Bilibili));
				while (i.hasNext()){
					int index = d->model->rowCount() + 1;
					QStandardItem *item = new QStandardItem;
					item->setData(QUrl(api.arg(task.code).arg(index)), UrlRole);
					item->setData((task.code + "#%1").arg(index), StrRole);
					item->setData(Page, NxtRole);
					item->setData(Utils::decodeXml(i.next().captured()), Qt::EditRole);
					d->model->appendRow(item);
				}
			}
			if (d->model->rowCount() > 0){
				emit stateChanged(task.state = Part);
			}
			else{
				QRegularExpression r = QRegularExpression("cid[=\":]*\\d+", QRegularExpression::CaseInsensitiveOption);
				QRegularExpressionMatchIterator i = r.globalMatch(video);
				while (i.hasNext()){
					QString m = i.next().captured();
					m = QRegularExpression("\\d+").match(m).captured();
					if (id.isEmpty()){
						id = m;
					}
					else if (id != m){
						id.clear();
						break;
					}
				}
				if (!id.isEmpty()){
					api = "http://comment.%1/%2.xml";
					api = api.arg(Utils::customUrl(Utils::Bilibili));
					forward(QNetworkRequest(api.arg(id)), File);
				}
                else{
                    emit stateChanged(203);
                    qDebug() << "Fail to load danmaku, try biliApi";
                    dequeue();
                }
            }
			break;
		}
		case File:
		{
			dumpDanmaku(reply->readAll(), Utils::Bilibili, false);
			emit stateChanged(task.state = None);
			dequeue();
			break;
		}
		}
	};
	auto avRegular = [](QString &code){
		code.remove(QRegularExpression("/index(?=_\\d+\\.html)"));
		QRegularExpression r("a(v(\\d+([#_])?(\\d+)?)?)?");
		r.setPatternOptions(QRegularExpression::CaseInsensitiveOption);
		return getRegular(r)(code);
	};
	d->pool.append({ avRegular, 0, avProcess });

	auto bbProcess = [this, avProcess](QNetworkReply *reply) {
		Q_D(Load);
		Task &task = d->queue.head();
		switch (task.state) {
		case None:
		{
			QString i = task.code.mid(2);
			QString u = "http://www.%1/bangumi/i/%2/";
			u = u.arg(Utils::customUrl(Utils::Bilibili)).arg(i);
			forward(QNetworkRequest(u), Page);
			break;
		}
		case Page:
		{
			d->model->clear();
			QString page(reply->readAll());
			QStringList list = page.split("<li data-index");

			if (list.size() < 2) {
				emit stateChanged(task.state = None);
				dequeue();
				break;
			}

			list.removeFirst();
			QListIterator<QString> iter(list);
			iter.toBack();
			while (iter.hasPrevious()) {
				QRegularExpression r;
				const QString &i = iter.previous();
				r.setPattern("(?<=href=\")[^\"]+");
				QString c = r.match(i).captured();
				fixCode(c);
				r.setPattern("(?<=<span>).+(?=</span>)");
				QString t = Utils::decodeXml(r.match(i).captured());

				QStandardItem *item = new QStandardItem;
				item->setData(c, StrRole);
				item->setData(None, NxtRole);
				item->setData(t, Qt::EditRole);
				d->model->appendRow(item);
			}
			emit stateChanged(task.state = Part);
		}
		}
	};

	auto bbRegular = [](QString &code) {
		code.replace(QRegularExpression("bangumi/i/(?=\\d+)"), "bb");
		QRegularExpression r("b(b(\\d+)?)?");
		r.setPatternOptions(QRegularExpression::CaseInsensitiveOption);
		return getRegular(r)(code);
	};
	d->pool.append({ bbRegular, 0, bbProcess });

	auto acProcess = [this](QNetworkReply *reply){
		Q_D(Load);
		Task &task = d->queue.head();
		int sharp = task.code.indexOf(QRegularExpression("[#_]"));
		switch (task.state){
		case None:
		{
			QString i = task.code.mid(2, sharp - 2);
			QString p = sharp == -1 ? QString() : task.code.mid(sharp + 1);
			QString url("http://www.%1/v/ac%2");
			url = url.arg(Utils::customUrl(Utils::AcFun)).arg(i);
			if (!p.isEmpty()){
				url += QString("_%1").arg(p);
			}
			forward(QNetworkRequest(url), Page);
			break;;
		}
		case Page:
		{
			d->model->clear();
			QRegularExpressionMatchIterator match = QRegularExpression("data-vid.*?</a>").globalMatch(reply->readAll());
			while (match.hasNext()){
				QStandardItem *item = new QStandardItem;
				QString part = match.next().captured();
				QRegularExpression r;
				r.setPattern("(?<=>)[^>]+?(?=</a>)");
				item->setData(Utils::decodeXml(r.match(part).captured()), Qt::EditRole);
				r.setPattern("(?<=data-vid=\").+?(?=\")");
				QString next("http://static.comment.%1/V2/%2?pageSize=1000&pageNo=1");
				next = next.arg(Utils::customUrl(Utils::AcFun)).arg(r.match(part).captured());
				item->setData(next, UrlRole);
				item->setData((task.code + "#%1").arg(d->model->rowCount() + 1), StrRole);
				item->setData(File, NxtRole);
				d->model->appendRow(item);
			}
			if (sharp == -1 && d->model->rowCount() >= 2){
				emit stateChanged(task.state = Part);
			}
			else{
				int i = sharp == -1 ? 0 : task.code.mid(sharp + 1).toInt() - 1;
				if (i >= 0 && i < d->model->rowCount()){
					forward(QNetworkRequest(d->model->item(i)->data(UrlRole).toUrl()), File);
				}
				else{
					emit stateChanged(203);
					dequeue();
				}
			}
			break;
		}
		case File:
		{
			QByteArray data = reply->readAll();
			if (data != "[[],[],[]]"){
				QNetworkRequest &request = task.request;
				QUrl url = request.url();
				int page = QUrlQuery(url).queryItemValue("pageNo").toInt();
				url.setQuery(QString());
				request.setUrl(url);
				dumpDanmaku(data, Utils::AcFun, false);
				QUrlQuery query;
				query.addQueryItem("pageSize", "1000");
				query.addQueryItem("pageNo", QString::number(page + 1));
				url.setQuery(query);
				request.setUrl(url);
				forward(request, File);
			}
			else{
				emit stateChanged(task.state = None);
				dequeue();
			}
			break;
		}
		}
	};
	auto acRegular = getRegular(QRegularExpression("a(c(\\d+([#_])?(\\d+)?)?)?", QRegularExpression::CaseInsensitiveOption));
	d->pool.append({ acRegular, 0, acProcess });

	auto abProcess = [this, acProcess](QNetworkReply *reply){
		Q_D(Load);
		Task &task = d->queue.head();
		int sharp = task.code.indexOf(QRegularExpression("[#_]"));
		switch (task.state){
		case None:
		{
			QString url("http://www.%1/bangumi/video/page?bangumiId=%2&pageSize=30&pageNo=%3&order=2");
			url = url.arg(Utils::customUrl(Utils::AcFun)).arg(task.code.mid(2, sharp - 2));
			url = url.arg(sharp == -1 ? 1 : (task.code.mid(sharp + 1).toInt() - 1) / 30 + 1);
			forward(QNetworkRequest(url), Page);
			break;
		}
		case Page:
		{
			if (sharp != -1){
				QJsonObject data = QJsonDocument::fromJson(reply->readAll()).object()["data"].toObject();
				int i = task.code.mid(sharp + 1).toInt();
				if (i > 0){
					i = (i - 1) % 30;
				}
				else{
					i = data["totalCount"].toInt();
					if (i > 30){
						task.code = task.code.left(sharp) + QString("#%1").arg(i);
						task.state = None;
						task.processer->process(nullptr);
						break;
					}
				}
				QJsonArray list = data["list"].toArray();
				if (i < 0 || i >= list.size()){
					emit stateChanged(203);
					dequeue();
					break;
				}
				QString head("http://static.comment.%1/V2/%2?pageSize=1000&pageNo=1");
				head = head.arg(Utils::customUrl(Utils::AcFun));
				head = head.arg(list[i].toObject()["danmakuId"].toString());
				forward(QNetworkRequest(head), File);
				break;
			}
			else{
				d->model->clear();
			}
		}
		case Part:
		{
			QJsonObject info = QJsonDocument::fromJson(reply->readAll()).object();
			if (!info["success"].toBool() && d->model->rowCount() == 0){
				emit stateChanged(info["status"].toInt());
				dequeue();
			}
			QJsonObject data = info["data"].toObject();
			for (const QJsonValue &value : data["list"].toArray()){
				QStandardItem *item = new QStandardItem;
				QJsonObject data = value.toObject();
				item->setData(data["title"].toString(), Qt::EditRole);
				QString head("http://static.comment.%1/V2/%2?pageSize=1000&pageNo=1");
				head = head.arg(Utils::customUrl(Utils::AcFun)).arg(data["danmakuId"].toString());
				item->setData(head, UrlRole);
				item->setData((task.code + "#%1").arg(d->model->rowCount() + 1), StrRole);
				item->setData(File, NxtRole);
				d->model->appendRow(item);
			}
			if (task.state != Part){
				emit stateChanged(task.state = Part);
			}
			if (data["pageNo"].toInt() < data["totalPage"].toInt()){
				QUrl url = reply->request().url();
				auto arg = QUrlQuery(url).queryItems();
				for (auto &p : arg){
					if (p.first == "pageNo"){
						p.second = QString::number(p.second.toInt() + 1);
						break;
					}
				}
				QUrlQuery query;
				query.setQueryItems(arg);
				url.setQuery(query);
				d->remain.insert(d->manager.get(QNetworkRequest(url)));
			}
			break;
		}
		case File:
		{
			acProcess(reply);
			break;
		}
		}
	};
	auto abRegular = getRegular(QRegularExpression("a(b(\\d+([#_])?(\\d+)?)?)?", QRegularExpression::CaseInsensitiveOption));
	d->pool.append({ abRegular, 0, abProcess });

	auto ccProcess = [this](QNetworkReply *reply){
		Q_D(Load);
		Task &task = d->queue.head();
		int sharp = task.code.indexOf(QRegularExpression("[#_]"));
		switch (task.state){
		case None:
		{
			QString i = task.code.mid(2, sharp - 2);
			QString p = sharp == -1 ? QString() : task.code.mid(sharp + 1);
			QString url("http://www.%1/play/h%2/");
			url = url.arg(Utils::customUrl(Utils::TuCao)).arg(i);
			if (!p.isEmpty()){
				url += QString("#%1").arg(p);
			}
			forward(QNetworkRequest(url), Page);
			break;
		}
		case Page:
		{
			QString page = reply->readAll();
			d->model->clear();
			QRegularExpressionMatch m;
			QRegularExpression r("(?<=<li>)[^<]*(?=</li>)");
			m = r.match(page, page.indexOf("<ul id=\"player_code\""));
			QStringList list = m.captured().split("**");
			m = r.match(page, m.capturedEnd());
			QString code = m.captured();
			for (const QString &iter : list){
				QStandardItem *item = new QStandardItem;
				item->setData(iter.mid(iter.indexOf('|') + 1), Qt::EditRole);
				QString api("http://www.%1/index.php?m=mukio&c=index&a=init&playerID=%2");
				api = api.arg(Utils::customUrl(Utils::TuCao)).arg((code + "-%1").arg(d->model->rowCount()));
				item->setData(api, UrlRole);
				item->setData((task.code + "#%1").arg(d->model->rowCount() + 1), StrRole);
				item->setData(File, NxtRole);
				d->model->appendRow(item);
			}
			if (sharp == -1 && d->model->rowCount() >= 2){
				emit stateChanged(task.state = Part);
			}
			else{
				int i = sharp == -1 ? 0 : task.code.mid(sharp + 1).toInt() - 1;
				if (i >= 0 && i < d->model->rowCount()){
					forward(QNetworkRequest(d->model->item(i)->data(UrlRole).toUrl()), File);
				}
				else{
					emit stateChanged(203);
					dequeue();
				}
			}
			break;
		}
		case File:
		{
			dumpDanmaku(reply->readAll(), Utils::TuCao, false);
			emit stateChanged(task.state = None);
			dequeue();
			break;
		}
		}
	};
	auto ccRegular = [](QString &code){
		code.replace(QRegularExpression("[Hh](?=\\d)"), "cc");
		QRegularExpression r("c(c(\\d+([#_])?(\\d+)?)?)?");
		r.setPatternOptions(QRegularExpression::CaseInsensitiveOption);
		return getRegular(r)(code);
	};
	d->pool.append({ ccRegular, 0, ccProcess });

	d->pool.append(Proc());
	Proc *directProc = &d->pool.last();
	directProc->process = [this](QNetworkReply *reply){
		Q_D(Load);
		Task &task = d->queue.head();
		switch (task.state){
		case None:
		{
			QUrl url = QUrl::fromUserInput(task.code);
			task.request.setUrl(url);
			task.state = File;
			forward();
			break;
		}
		case File:
		{
			Record load;
			QUrl url = reply->url();
			QByteArray data(reply->readAll());
			load.source = url.url();
			load.access = url.isLocalFile() ? url.toLocalFile() : load.source;
			load.string = QFileInfo(task.code).fileName();
			load.delay = task.delay;
			QString head = Utils::decodeTxt(data.left(512));
			if (head.startsWith("[Script Info]")){
				load.danmaku = Parse::parseComment(data, Utils::ASS);
			}
			else if (!head.startsWith("<?xml")){
				load.danmaku = Parse::parseComment(data, Utils::AcFun);
			}
			else if (head.indexOf("<packet>") != -1){
				load.danmaku = Parse::parseComment(data, Utils::Niconico);
			}
			else if (head.indexOf("<i>") != -1){
				load.danmaku = Parse::parseComment(data, Utils::Bilibili);
				QString i = QRegularExpression("(?<=<chatid>)\\d+(?=</chatid>)").match(head).captured();
				if (!i.isEmpty()){
					load.source = "http://comment.%1/%2.xml";
					load.source = load.source.arg(Utils::customUrl(Utils::Bilibili)).arg(i);
				}
			}
			else if (head.indexOf("<c>") != -1){
				load.danmaku = Parse::parseComment(data, Utils::AcfunLocalizer);
			}
			if (load.delay != 0){
				for (Comment &c : load.danmaku){
					c.time += load.delay;
				}
			}
			Danmaku::instance()->appendToPool(&load);
			emit stateChanged(task.state = None);
			dequeue();
			break;
		}
		}
	};
	directProc->priority = -100;
	directProc->regular = [this, directProc](QString &code){
		if (code.startsWith("full?") || code.startsWith("hist?")){
			code.clear();
			return false;
		}
		QUrl u = QUrl::fromUserInput(code);
		if (!u.host().isEmpty() && !u.path().isEmpty()){
			return true;
		}
		if (QFileInfo(code).exists()){
			return true;
		}
		code.clear();
		return false;
	};

	auto fullBiProcess = [this](QNetworkReply *reply){
		Q_D(Load);
		Task &task = d->queue.head();
		switch (task.state) {
		case None:
		{
			emit progressChanged(0);
			QString api("http://comment.%1/rolldate,%2");
			api = api.arg(Utils::customUrl(Utils::Bilibili));
			task.code = QUrlQuery(task.code.mid(5)).queryItemValue("source");
			forward(QNetworkRequest(api.arg(QFileInfo(task.code).baseName())), Page);
			break;
		}
		case Page:
		{
			QByteArray data = reply->readAll();
			QJsonArray date = QJsonDocument::fromJson(data).array();
			if (date.isEmpty()) {
				emit stateChanged(203);
				dequeue();
				break;
			}
			QJsonObject head = date.first().toObject();
			QString url("http://comment.%1/dmroll,%2,%3");
			url = url.arg(Utils::customUrl(Utils::Bilibili));
			url = url.arg(head["timestamp"].toVariant().toInt());
			url = url.arg(QFileInfo(task.code).baseName());
			QNetworkRequest request(url);
			request.setAttribute(QNetworkRequest::User, data);
			forward(request, Code);
			break;
		}
		case Code:
		{
			QByteArray data = task.request.attribute(QNetworkRequest::User).toByteArray();
			QJsonArray date = QJsonDocument::fromJson(data).array();
			QMap<int, int> count;
			for (auto iter : date) {
				QJsonObject item = iter.toObject();
				count[item["timestamp"].toVariant().toInt()] += item["new"].toVariant().toInt();
			}

			data = reply->readAll();
			if (count.size() >= 2) {
				int max = QRegularExpression("(?<=\\<max_count\\>).+(?=\\</max_count\\>)").match(data).captured().toInt();
				int now = 0;

				auto getHistory = [d, &count, &task](int date) {
					QString url("http://comment.%1/dmroll,%2,%3");
					url = url.arg(Utils::customUrl(Utils::Bilibili));
					url = url.arg(date);
					url = url.arg(QFileInfo(task.code).baseName());
					return d->manager.get(QNetworkRequest(url));
				};

				for (auto iter = count.begin() + 1;; ++iter) {
					now += iter.value();
					if (iter + 1 == count.end()) {
						d->remain += getHistory(iter.key());
						break;
					}
					else if (now + (iter + 1).value() > max) {
						d->remain += getHistory(iter.key());
						now = 0;
					}
				}

				auto pool = QSharedPointer<QVector<Parse::ResultDelegate>>::create();
				pool->append(Parse::parseComment(data, Utils::Bilibili));

				double total = d->remain.size() + 2;
				for (QNetworkReply *iter : d->remain) {
					connect(iter, &QNetworkReply::finished, [=, &task]() {
						QByteArray data = iter->readAll();
						pool->append(Parse::parseComment(data, Utils::Bilibili));
						switch (iter->error()) {
						case QNetworkReply::NoError:
							emit progressChanged((total - d->remain.size()) / total);
						case QNetworkReply::OperationCanceledError:
							if (d->remain.isEmpty() && !pool->empty()) {
								Record load;
								load.full = true;
								for (auto &iter : *pool) {
									load.danmaku.append(iter);
								}
								load.source = task.code;
								Danmaku::instance()->appendToPool(&load);
								emit stateChanged(task.state = None);
								dequeue();
							}
						default:
							break;
						}
					});
				}

				emit progressChanged(2 / total);
				emit stateChanged(task.state = File);
				break;
			}
			else {
				emit progressChanged(1);
				dumpDanmaku(data, Utils::Bilibili, true);
				emit stateChanged(task.state = None);
				dequeue();
				break;
			}
		}
		}
	};

	auto fullBiRegular = QRegularExpression("^full\\?source=http://comment\\.bilibili\\.com/\\d+\\.xml$");
	fullBiRegular.setPatternOptions(QRegularExpression::CaseInsensitiveOption);
	d->pool.append({ getRegular(fullBiRegular), 100, fullBiProcess });

	auto histBiProcess = [this](QNetworkReply *reply){
		Q_D(Load);
		Task &task = d->queue.head();
		switch (task.state){
		case None:
		{
			QUrlQuery query(task.code.mid(5));
			task.code = query.queryItemValue("source");
			QString cid = QFileInfo(task.code).baseName();
			QString dat = query.queryItemValue("date");
			QString url;
			QNetworkRequest request;
			if (dat != "0" && dat.toUInt() != QDateTime(QDate::currentDate()).toTime_t()){
				url = QString("http://comment.%1/dmroll,%2,%3");
				url = url.arg(Utils::customUrl(Utils::Bilibili));
				url = url.arg(dat).arg(cid);
				int limit = QDateTime(QDateTime::fromTime_t(dat.toInt()).date().addDays(1)).toTime_t();
				request.setAttribute(QNetworkRequest::User, limit);
			}
			else{
				url = QString("http://comment.%1/%2.xml").arg(Utils::customUrl(Utils::Bilibili));
				url = url.arg(cid);
			}
			request.setUrl(url);
			forward(request, File);
			break;
		}
		case File:
		{
			Record load;
			load.danmaku = Parse::parseComment(reply->readAll(), Utils::Bilibili);
			load.source = task.code;
			for (Record &iter : Danmaku::instance()->getPool()){
				if (iter.source == load.source){
					iter.full = false;
					iter.danmaku.clear();
					iter.limit = 1;
					break;
				}
			}
			load.limit = task.request.attribute(QNetworkRequest::User).toInt();
			Danmaku::instance()->appendToPool(&load);
			emit stateChanged(task.state = None);
			dequeue();
			break;
		}
		}
	};
	auto histBiRegular = QRegularExpression("^hist\\?source=http://comment\\.bilibili\\.com/\\d+\\.xml&date=\\d+$");
	histBiRegular.setPatternOptions(QRegularExpression::CaseInsensitiveOption);
	d->pool.append({ getRegular(histBiRegular), 100, histBiProcess });

	connect(this, &Load::stateChanged, [this](int code){
		switch (code){
		case None:
		case Page:
		case Part:
		case Code:
		case File:
			break;
		default:
		{
			Q_D(Load);
			if (!d->tryNext()){
				emit errorOccured(code);
			}
			break;
		}
		}
	});
}
コード例 #15
0
ファイル: wizsync.cpp プロジェクト: qqshow/WizQTClient
void CWizSync::startDownloadDeleteds()
{
    Q_EMIT processLog(tr("downloading deleted objects list"));
    Q_EMIT progressChanged(progressOnLogin);
    downloadNextDeleteds(m_db.GetObjectVersion(WIZDELETEDGUIDDATA::ObjectName()));
}
コード例 #16
0
void MusicSearchEngine::doSearch(const QStringList &delta)
{
	//qDebug() << Q_FUNC_INFO << delta;
	MusicSearchEngine::isScanning = true;
	QList<QDir> locations;
	QStringList pathsToSearch = delta.isEmpty() ? SettingsPrivate::instance()->musicLocations() : delta;
	for (QString musicPath : pathsToSearch) {
		QDir location(musicPath);
		location.setFilter(QDir::AllDirs | QDir::Files | QDir::Hidden | QDir::NoDotAndDotDot);
		locations.append(location);
	}

	int entryCount = 0;
	// QDirIterator class is very fast to scan large directories
	for (QDir location : locations) {
		QDirIterator it(location.absolutePath(), QDir::AllEntries | QDir::Hidden | QDir::NoDotAndDotDot, QDirIterator::Subdirectories);
		while (it.hasNext()) {
			it.next();
			entryCount++;
		}
	}

	int currentEntry = 0;
	int percent = 1;
	bool atLeastOneAudioFileWasFound = false;
	bool isNewDirectory = false;

	QString coverPath;
	QString lastFileScannedNextToCover;

	QStringList suffixes = FileHelper::suffixes(FileHelper::All);

	for (QDir location : locations) {
		QDirIterator it(location.absolutePath(), QDir::AllEntries | QDir::Hidden | QDir::NoDotAndDotDot, QDirIterator::Subdirectories);
		while (it.hasNext()) {
			QString entry = it.next();
			QFileInfo qFileInfo(entry);
			currentEntry++;

			// Directory has changed: we can discard cover
			if (qFileInfo.isDir()) {
				if (!coverPath.isEmpty() && !lastFileScannedNextToCover.isEmpty()) {
					emit scannedCover(coverPath, lastFileScannedNextToCover);
					coverPath.clear();
				}
				isNewDirectory = true;
				atLeastOneAudioFileWasFound = false;
				lastFileScannedNextToCover.clear();
				continue;
			} else if (qFileInfo.suffix().toLower() == "jpg" || qFileInfo.suffix().toLower() == "png") {
				if (atLeastOneAudioFileWasFound) {
					coverPath = qFileInfo.absoluteFilePath();
					emit scannedCover(coverPath, lastFileScannedNextToCover);
					coverPath.clear();
				} else if (isNewDirectory) {
					coverPath = qFileInfo.absoluteFilePath();
				}
			} else if (suffixes.contains(qFileInfo.suffix())) {
				emit scannedFile(qFileInfo.absoluteFilePath());
				atLeastOneAudioFileWasFound = true;
				lastFileScannedNextToCover = qFileInfo.absoluteFilePath();
				isNewDirectory = false;
			}

			if (currentEntry * 100 / entryCount > percent) {
				percent = currentEntry * 100 / entryCount;
				emit progressChanged(percent);
			}
		}
		atLeastOneAudioFileWasFound = false;
	}
	emit searchHasEnded();
	MusicSearchEngine::isScanning = false;
}
コード例 #17
0
ファイル: wizsync.cpp プロジェクト: qqshow/WizQTClient
void CWizSync::onDownloadObjectsDataCompleted()
{
    Q_EMIT progressChanged(progressObjectDownloaded);

    stopSync();
}
コード例 #18
0
void ECWThread::updateProgressBar(int val)
{
    emit progressChanged(val);
}
コード例 #19
0
/**
 * Called by the "Start" button.  Sets up the meta data and enables the
 * buttons to perform six point calibration of the magnetometer (optionally
 * accel) to compute the scale and bias of this sensor based on the current
 * home location magnetic strength.
 */
void SixPointCalibrationModel::start(bool calibrateAccel, bool calibrateMag)
{
    calibratingAccel = calibrateAccel;
    calibratingMag   = calibrateMag;

    started();

    // check if Homelocation is set
    HomeLocation::DataFields homeLocationData = homeLocation->getData();
    if (!homeLocationData.Set) {
        displayInstructions(tr("Home location not set, please set your home location and retry."), WizardModel::Warn);
        displayInstructions(tr("Aborting calibration!"), WizardModel::Failure);
        stopped();
        return;
    }

    // Store and reset board rotation before calibration starts
    storeAndClearBoardRotation();

    // Calibration accel
    AccelGyroSettings::DataFields accelGyroSettingsData = accelGyroSettings->getData();
    memento.accelGyroSettingsData = accelGyroSettingsData;

    accelGyroSettingsData.accel_scale[AccelGyroSettings::ACCEL_SCALE_X] = 1;
    accelGyroSettingsData.accel_scale[AccelGyroSettings::ACCEL_SCALE_Y] = 1;
    accelGyroSettingsData.accel_scale[AccelGyroSettings::ACCEL_SCALE_Z] = 1;
    accelGyroSettingsData.accel_bias[AccelGyroSettings::ACCEL_BIAS_X]   = 0;
    accelGyroSettingsData.accel_bias[AccelGyroSettings::ACCEL_BIAS_Y]   = 0;
    accelGyroSettingsData.accel_bias[AccelGyroSettings::ACCEL_BIAS_Z]   = 0;

    accelGyroSettings->setData(accelGyroSettingsData);

    // Calibration mag
    RevoCalibration::DataFields revoCalibrationData = revoCalibration->getData();
    memento.revoCalibrationData = revoCalibrationData;

    // Reset the transformation matrix to identity
    for (int i = 0; i < RevoCalibration::MAG_TRANSFORM_R2C2; i++) {
        revoCalibrationData.mag_transform[i] = 0;
    }
    revoCalibrationData.mag_transform[RevoCalibration::MAG_TRANSFORM_R0C0] = 1;
    revoCalibrationData.mag_transform[RevoCalibration::MAG_TRANSFORM_R1C1] = 1;
    revoCalibrationData.mag_transform[RevoCalibration::MAG_TRANSFORM_R2C2] = 1;
    revoCalibrationData.mag_bias[RevoCalibration::MAG_BIAS_X] = 0;
    revoCalibrationData.mag_bias[RevoCalibration::MAG_BIAS_Y] = 0;
    revoCalibrationData.mag_bias[RevoCalibration::MAG_BIAS_Z] = 0;

    // Disable adaptive mag nulling
    revoCalibrationData.MagBiasNullingRate = 0;

    revoCalibration->setData(revoCalibrationData);

    // Calibration AuxMag
    AuxMagSettings::DataFields auxMagSettingsData = auxMagSettings->getData();
    memento.auxMagSettings = auxMagSettingsData;

    // Reset the transformation matrix to identity
    for (int i = 0; i < AuxMagSettings::MAG_TRANSFORM_R2C2; i++) {
        auxMagSettingsData.mag_transform[i] = 0;
    }
    auxMagSettingsData.mag_transform[AuxMagSettings::MAG_TRANSFORM_R0C0] = 1;
    auxMagSettingsData.mag_transform[AuxMagSettings::MAG_TRANSFORM_R1C1] = 1;
    auxMagSettingsData.mag_transform[AuxMagSettings::MAG_TRANSFORM_R2C2] = 1;
    auxMagSettingsData.mag_bias[AuxMagSettings::MAG_BIAS_X] = 0;
    auxMagSettingsData.mag_bias[AuxMagSettings::MAG_BIAS_Y] = 0;
    auxMagSettingsData.mag_bias[AuxMagSettings::MAG_BIAS_Z] = 0;

    // Disable adaptive mag nulling
    auxMagSettingsData.MagBiasNullingRate = 0;

    auxMagSettings->setData(auxMagSettingsData);

    QThread::usleep(100000);

    mag_accum_x.clear();
    mag_accum_y.clear();
    mag_accum_z.clear();

    mag_fit_x.clear();
    mag_fit_y.clear();
    mag_fit_z.clear();

    // Need to get as many accel updates as possible
    memento.accelStateMetadata = accelState->getMetadata();
    if (calibrateAccel) {
        UAVObject::Metadata mdata = accelState->getMetadata();
        UAVObject::SetFlightTelemetryUpdateMode(mdata, UAVObject::UPDATEMODE_PERIODIC);
        mdata.flightTelemetryUpdatePeriod = 100;
        accelState->setMetadata(mdata);
    }

    // Need to get as many mag updates as possible
    memento.magSensorMetadata    = magSensor->getMetadata();
    memento.auxMagSensorMetadata = auxMagSensor->getMetadata();

    if (calibrateMag) {
        UAVObject::Metadata mdata = magSensor->getMetadata();
        UAVObject::SetFlightTelemetryUpdateMode(mdata, UAVObject::UPDATEMODE_PERIODIC);
        mdata.flightTelemetryUpdatePeriod = 100;
        magSensor->setMetadata(mdata);

        mdata = auxMagSensor->getMetadata();
        UAVObject::SetFlightTelemetryUpdateMode(mdata, UAVObject::UPDATEMODE_PERIODIC);
        mdata.flightTelemetryUpdatePeriod = 100;
        auxMagSensor->setMetadata(mdata);
    }

    // reset dirty state to forget previous unsaved runs
    m_dirty = false;

    if (calibrateMag) {
        currentSteps = &calibrationStepsMag;
    } else {
        currentSteps = &calibrationStepsAccelOnly;
    }

    position = 0;

    // Show instructions and enable controls
    progressChanged(0);
    displayInstructions((*currentSteps)[0].instructions, WizardModel::Prompt);
    showHelp((*currentSteps)[0].visualHelp);
    savePositionEnabledChanged(true);
}
コード例 #20
0
void AMExportController::continueScanExport()
{
	if(state_ != Exporting)
		return;	// done, or paused. Don't keep going.

	// 0. emit progress and signals
	emit progressChanged(exportScanIndex_, scanCount());

	// 1. Check for finished:
	if(exportScanIndex_ >= scanCount()) {
		emit stateChanged(state_ = Finished);

		// Reset whether the exporter should overwrite files with matching filenames.
		exporter_->setOverwriteOption(AMExporter::Default);

		QString message = "Exported " % QString::number(succeededCount()) % " scans.";
		if(failedCount())
			message.append("  (" % QString::number(failedCount()) % " scans could not be exported.)");
		AMErrorMon::report(AMErrorReport(this, AMErrorReport::Information, 0, message));

		AMUser::user()->setLastExportDestination(destinationFolderPath());
		AMUser::user()->storeToDb(AMUser::user()->database());

		deleteLater();
		return; // We're done!
	}

	try {
		// 2. Load scan from db and check loaded successfully


		AMScan* scan = 0;
		AMDbObject* databaseObject = 0;
		if(usingScanURLs_){
			const QUrl& url = scanURLsToExport_.at(exportScanIndex_);
			AMDatabase* db = 0;
			QStringList path;
			QString tableName;
			int id = 0;
			bool idOkay = false;

			// parse the URL and make sure it's valid
			if(!( url.scheme() == "amd" &&
				  (db = AMDatabase::database(url.host())) &&
				  (path = url.path().split('/', QString::SkipEmptyParts)).count() == 2 &&
				  (id = path.at(1).toInt(&idOkay)) > 0 &&
				  idOkay == true &&
				  (tableName = path.at(0)).isEmpty() == false
				  ))
				throw QString("The export system couldn't understand the scan URL '" % url.toString() % "', so this scan has not been exported.");
			emit statusChanged(status_ = "Opening: " % url.toString());

			databaseObject = AMDbObjectSupport::s()->createAndLoadObjectAt(db, tableName, id);
			scan = qobject_cast<AMScan*>(databaseObject);

			if(!scan) {
				databaseObject->deleteLater();
				throw QString("The export system couldn't load a scan out of the database (" % url.toString() % "), so this scan has not been exported.");
			}
		}

		else if(usingScanObjects_) {
			scan = scanObjectsToExport_.at(exportScanIndex_);
			if(!scan)
				throw QString("An invalid scan reference was provided, so this scan has not been exported.");
		}

		emit statusChanged(status_ = "Opening: " % scan->name());	// this is kinda pointless...
		emit statusChanged(status_ = "Writing: " % scan->fullName());

		// 3. Check that it can be exported with the exporter and option selected
		if(!exporter_->isValidFor(scan, option_)) {
			QString err("The exporter '" % exporter_->description() % "' and the template '" % option_->name() % "' are not compatible with this scan (" % scan->fullName() % "), so it has not been exported.");
			emit statusChanged(status_ = err);

			if (usingScanURLs_)
				scan->deleteLater();

			throw err;
		}


		// 4. Export
		//    4.1 check and create the export folder for the current run
		QString destinationFolderPathWithRun = destinationFolderPath_;

		exporter_->setCurrentScan(scan); // we must set this, otherwise we can't get the name of the current run
		QString currentRunExportFilePath = exporter_->currentRunExportFilePath();
		if(currentRunExportFilePath.length() > 0) {
			QDir exportDir;
			exportDir.setCurrent(destinationFolderPath_);
			if  (!exportDir.entryList(QDir::AllDirs).contains(currentRunExportFilePath)) {
				if(!exportDir.mkdir(currentRunExportFilePath)){
					QString err("Could not create the export folder." % exportDir.absolutePath());
					emit statusChanged(status_ = err);
					throw err;
				}
			}

			destinationFolderPathWithRun = destinationFolderPathWithRun % "/" % currentRunExportFilePath;
		}

		//    4.2 export
		QString writtenFile = exporter_->exportScan(scan, destinationFolderPathWithRun, option_, exportScanIndex_);
		if(writtenFile.isNull()) {
			QString err("Export failed for scan '" % scan->fullName() % " to " % destinationFolderPathWithRun % "'.");
			emit statusChanged(status_ = err);

			if (usingScanURLs_)
				scan->deleteLater();

			throw err;
		}

		emit statusChanged(status_ = "Wrote: " % writtenFile);
		succeededCount_++;

		if (usingScanURLs_)
			scan->deleteLater();
	}

	catch(QString errMsg) {
		failedCount_++;
		AMErrorMon::report(AMErrorReport(this, AMErrorReport::Alert, -1, errMsg));
	}


	// 5. increment exportScanIndex_ and re-schedule next one
	exportScanIndex_++;
	QTimer::singleShot(5, this, SLOT(continueScanExport()));

}
コード例 #21
0
AccountSettings::AccountSettings(QWidget *parent, Qt::WindowFlags flags)
    : QDialog(parent, flags),
      preExisting(false),
      deleteBatchSize(0),
      deleteProgress(0)
{
    setWindowTitle(tr("Accounts"));
    QVBoxLayout *vb = new QVBoxLayout(this);
    vb->setContentsMargins(0, 0, 0, 0);

    accountModel = new QMailAccountListModel(this);
    accountModel->setKey(QMailAccountKey::status(QMailAccount::UserEditable, QMailDataComparator::Includes));
    accountModel->setSortKey(QMailAccountSortKey::id(Qt::AscendingOrder));
    connect(accountModel,SIGNAL(rowsInserted(QModelIndex,int,int)),this,SLOT(updateActions()));
    connect(accountModel,SIGNAL(rowsRemoved(QModelIndex,int,int)),this,SLOT(updateActions()));

    accountView = new QListView(this);
    accountView->setContextMenuPolicy(Qt::ActionsContextMenu);
    accountView->setModel(accountModel);

    if (accountModel->rowCount())
        accountView->setCurrentIndex(accountModel->index(0, 0));
    else //no accounts so automatically add
        QTimer::singleShot(0,this,SLOT(addAccount()));

    addAccountAction = new QAction( Qtmail::icon("add"), tr("New"), this );
    connect(addAccountAction, SIGNAL(triggered()), this, SLOT(addAccount()));

    editAccountAction = new QAction(Qtmail::icon("settings"),tr("Edit"), this);
    connect(editAccountAction,SIGNAL(triggered()),this,SLOT(editCurrentAccount()));
    accountView->addAction(editAccountAction);

    resetAccountAction = new QAction( Qtmail::icon("reset"), tr("Reset"), this );
    connect(resetAccountAction, SIGNAL(triggered()), this, SLOT(resetAccount()));
    accountView->addAction(resetAccountAction);

    removeAccountAction = new QAction( Qtmail::icon("remove"), tr("Remove"), this );
    connect(removeAccountAction, SIGNAL(triggered()), this, SLOT(removeAccount()));
    accountView->addAction(removeAccountAction);

    QToolBar *buttonBar = new QToolBar(this);
    buttonBar->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
    buttonBar->addAction(addAccountAction);
    buttonBar->addSeparator();
    buttonBar->addAction(editAccountAction);
    buttonBar->addAction(resetAccountAction);
    buttonBar->addAction(removeAccountAction);

    vb->addWidget(buttonBar);
    vb->addWidget(accountView);

    statusDisplay = new StatusBar(this);
    statusDisplay->setDetailsButtonVisible(false);
    statusDisplay->setVisible(false);


    vb->addWidget(statusDisplay);

    connect(accountView, SIGNAL(activated(QModelIndex)),
            this, SLOT(editCurrentAccount()));

    retrievalAction = new QMailRetrievalAction(this);
    connect(retrievalAction, SIGNAL(activityChanged(QMailServiceAction::Activity)),
            this, SLOT(activityChanged(QMailServiceAction::Activity)));
    connect(retrievalAction, SIGNAL(progressChanged(uint, uint)),
            this, SLOT(displayProgress(uint, uint)));

    transmitAction = new QMailTransmitAction(this);
    connect(transmitAction, SIGNAL(activityChanged(QMailServiceAction::Activity)),
            this, SLOT(activityChanged(QMailServiceAction::Activity)));
    connect(transmitAction, SIGNAL(progressChanged(uint, uint)),
            this, SLOT(displayProgress(uint, uint)));
}
コード例 #22
0
void PlaybackController::updateIndexPosition()
{
	emit progressChanged(progress());
	if(m_indexloader)
		emit indexPositionChanged(m_reader->currentIndex());
}
コード例 #23
0
void BlinkyPendantUploader::setProgress(int newProgress)
{
    progress = newProgress;
    emit(progressChanged(static_cast<float>(progress)/10));
}
コード例 #24
0
ファイル: kodidownload.cpp プロジェクト: AchimTuran/kodimote
void KodiDownload::setProgress(qint64 progress)
{
    m_progress = progress;
    emit progressChanged();
}
コード例 #25
0
void BlinkyTapeUploader::setProgress(int newProgress) {
    progress = newProgress;
    emit(progressChanged(progress));
}
コード例 #26
0
/*!
    Takes the \a helpData and generates a new documentation
    set from it. The Qt compressed help file is written to \a
    outputFileName. Returns true on success, otherwise false.
*/
bool QHelpGenerator::generate(QHelpDataInterface *helpData,
                              const QString &outputFileName)
{
    emit progressChanged(0);
    d->error.clear();
    if (!helpData || helpData->namespaceName().isEmpty()) {
        d->error = tr("Invalid help data!");
        return false;
    }

    QString outFileName = outputFileName;
    if (outFileName.isEmpty()) {
        d->error = tr("No output file name specified!");
        return false;
    }

    QFileInfo fi(outFileName);
    if (fi.exists()) {
        if (!fi.dir().remove(fi.fileName())) {
            d->error = tr("The file %1 cannot be overwritten!").arg(outFileName);
            return false;
        }
    }

    setupProgress(helpData);

    emit statusChanged(tr("Building up file structure..."));
    bool openingOk = true;
    {
        QSqlDatabase db = QSqlDatabase::addDatabase(QLatin1String("QSQLITE"), QLatin1String("builder"));
        db.setDatabaseName(outFileName);
        openingOk = db.open();
        if (openingOk)
            d->query = new QSqlQuery(db);
    }

    if (!openingOk) {
        d->error = tr("Cannot open data base file %1!").arg(outFileName);
        cleanupDB();
        return false;
    }

    d->query->exec(QLatin1String("PRAGMA synchronous=OFF"));
    d->query->exec(QLatin1String("PRAGMA cache_size=3000"));

    addProgress(1.0);
    createTables();
    insertFileNotFoundFile();
    insertMetaData(helpData->metaData());

    if (!registerVirtualFolder(helpData->virtualFolder(), helpData->namespaceName())) {
        d->error = tr("Cannot register namespace %1!").arg(helpData->namespaceName());
        cleanupDB();
        return false;
    }
    addProgress(1.0);

    emit statusChanged(tr("Insert custom filters..."));
    foreach (const QHelpDataCustomFilter &f, helpData->customFilters()) {
        if (!registerCustomFilter(f.name, f.filterAttributes, true)) {
            cleanupDB();
            return false;
        }
    }
    addProgress(1.0);

    int i = 1;
    QList<QHelpDataFilterSection>::const_iterator it = helpData->filterSections().constBegin();
    while (it != helpData->filterSections().constEnd()) {
        emit statusChanged(tr("Insert help data for filter section (%1 of %2)...")
            .arg(i++).arg(helpData->filterSections().count()));
        insertFilterAttributes((*it).filterAttributes());
        QByteArray ba;
        QDataStream s(&ba, QIODevice::WriteOnly);
        foreach (QHelpDataContentItem *itm, (*it).contents())
            writeTree(s, itm, 0);
        if (!insertFiles((*it).files(), helpData->rootPath(), (*it).filterAttributes())
            || !insertContents(ba, (*it).filterAttributes())
            || !insertKeywords((*it).indices(), (*it).filterAttributes())) {
            cleanupDB();
            return false;
        }
        ++it;
    }

    cleanupDB();
    emit progressChanged(100);
    emit statusChanged(tr("Documentation successfully generated."));
    return true;
}
コード例 #27
0
ファイル: dbusinterface.cpp プロジェクト: jonjahren/unity8
bool DBusInterface::handleMessage(const QDBusMessage& message, const QDBusConnection& connection)
{
    /* Check to make sure we're getting properties on our interface */
    if (message.type() != QDBusMessage::MessageType::MethodCallMessage) {
        return false;
    }

    /* Break down the path to just the app id */
    bool validpath = true;
    QString pathtemp = message.path();
    if (!pathtemp.startsWith(QLatin1String("/com/canonical/Unity/Launcher/"))) {
        validpath = false;
    }
    pathtemp.remove(QStringLiteral("/com/canonical/Unity/Launcher/"));
    if (pathtemp.indexOf('/') >= 0) {
        validpath = false;
    }

    /* Find ourselves an appid */
    QString appid = decodeAppId(pathtemp);

    // First handle methods of the Launcher interface
    if (message.interface() == QLatin1String("com.canonical.Unity.Launcher")) {
        if (message.member() == QLatin1String("Refresh")) {
            QDBusMessage reply = message.createReply();
            Q_EMIT refreshCalled();
            return connection.send(reply);
        }
    } else if (message.interface() == QLatin1String("com.canonical.Unity.Launcher.Item")) {
        // Handle methods of the Launcher-Item interface
        if (message.member() == QLatin1String("Alert") && validpath) {
            QDBusMessage reply = message.createReply();
            Q_EMIT alertCalled(appid);
            return connection.send(reply);
        }
    }

    // Now handle dynamic properties (for launcher emblems)
    if (message.interface() != QLatin1String("org.freedesktop.DBus.Properties")) {
        return false;
    }

    if (message.member() == QLatin1String("Get") && (message.arguments().count() != 2 || message.arguments()[0].toString() != QLatin1String("com.canonical.Unity.Launcher.Item"))) {
        return false;
    }

    if (message.member() == QLatin1String("Set") && (message.arguments().count() != 3 || message.arguments()[0].toString() != QLatin1String("com.canonical.Unity.Launcher.Item"))) {
        return false;
    }

    if (!validpath) {
        return false;
    }

    int index = m_launcherModel->findApplication(appid);
    LauncherItem *item = static_cast<LauncherItem*>(m_launcherModel->get(index));

    QVariantList retval;
    if (message.member() == QLatin1String("Get")) {
        QString cachedString = message.arguments()[1].toString();
        if (!item) {
            return false;
        }
        if (cachedString == QLatin1String("count")) {
            retval.append(QVariant::fromValue(QDBusVariant(item->count())));
        } else if (cachedString == QLatin1String("countVisible")) {
            retval.append(QVariant::fromValue(QDBusVariant(item->countVisible())));
        } else if (cachedString == QLatin1String("progress")) {
            retval.append(QVariant::fromValue(QDBusVariant(item->progress())));
        }
    } else if (message.member() == QLatin1String("Set")) {
        QString cachedString = message.arguments()[1].toString();
        if (cachedString == QLatin1String("count")) {
            int newCount = message.arguments()[2].value<QDBusVariant>().variant().toInt();
            if (!item || newCount != item->count()) {
                Q_EMIT countChanged(appid, newCount);
                notifyPropertyChanged(QStringLiteral("com.canonical.Unity.Launcher.Item"), encodeAppId(appid), QStringLiteral("count"), QVariant(newCount));
            }
        } else if (cachedString == QLatin1String("countVisible")) {
            bool newVisible = message.arguments()[2].value<QDBusVariant>().variant().toBool();
            if (!item || newVisible != item->countVisible()) {
                Q_EMIT countVisibleChanged(appid, newVisible);
                notifyPropertyChanged(QStringLiteral("com.canonical.Unity.Launcher.Item"), encodeAppId(appid), QStringLiteral("countVisible"), newVisible);
            }
        } else if (cachedString == QLatin1String("progress")) {
            int newProgress = message.arguments()[2].value<QDBusVariant>().variant().toInt();
            if (!item || newProgress != item->progress()) {
                Q_EMIT progressChanged(appid, newProgress);
                notifyPropertyChanged(QStringLiteral("com.canonical.Unity.Launcher.Item"), encodeAppId(appid), QStringLiteral("progress"), QVariant(newProgress));
            }
        }
    } else if (message.member() == QLatin1String("GetAll")) {
        if (item) {
            QVariantMap all;
            all.insert(QStringLiteral("count"), item->count());
            all.insert(QStringLiteral("countVisible"), item->countVisible());
            all.insert(QStringLiteral("progress"), item->progress());
            retval.append(all);
        }
    } else {
        return false;
    }

    QDBusMessage reply = message.createReply(retval);
    return connection.send(reply);
}
コード例 #28
0
ファイル: mediaplayer.cpp プロジェクト: koziolekrg/training
void MediaPlayer::changeProgress(int value)
{
    m_progress= value;
    emit progressChanged();

}
コード例 #29
0
void QAndroidOffscreenWebView::onProgressChanged(JNIEnv *, jobject, jobject webview, jint newProgress)
{
	Q_UNUSED(webview);
	emit progressChanged(newProgress);
}
コード例 #30
0
void QQuickAnimatedImage::movieRequestFinished()
{
    Q_D(QQuickAnimatedImage);

    if (d->reply) {
        d->redirectCount++;
        if (d->redirectCount < ANIMATEDIMAGE_MAXIMUM_REDIRECT_RECURSION) {
            QVariant redirect = d->reply->attribute(QNetworkRequest::RedirectionTargetAttribute);
            if (redirect.isValid()) {
                QUrl url = d->reply->url().resolved(redirect.toUrl());
                d->reply->deleteLater();
                setSource(url);
                return;
            }
        }

        d->redirectCount=0;
        d->_movie = new QMovie(d->reply);
    }

    if (!d->_movie->isValid()) {
        qmlInfo(this) << "Error Reading Animated Image File " << d->url.toString();
        delete d->_movie;
        d->_movie = 0;
        d->setImage(QImage());
        if (d->progress != 0) {
            d->progress = 0;
            emit progressChanged(d->progress);
        }
        d->status = Error;
        emit statusChanged(d->status);

        if (sourceSize() != d->oldSourceSize) {
            d->oldSourceSize = sourceSize();
            emit sourceSizeChanged();
        }
        if (isPlaying() != d->oldPlaying)
            emit playingChanged();
        return;
    }

    connect(d->_movie, SIGNAL(stateChanged(QMovie::MovieState)),
            this, SLOT(playingStatusChanged()));
    connect(d->_movie, SIGNAL(frameChanged(int)),
            this, SLOT(movieUpdate()));
    d->_movie->setCacheMode(QMovie::CacheAll);

    d->status = Ready;
    emit statusChanged(d->status);

    if (d->progress != 1.0) {
        d->progress = 1.0;
        emit progressChanged(d->progress);
    }

    bool pausedAtStart = d->paused;
    if (d->playing) {
        d->_movie->start();
    }
    if (pausedAtStart)
        d->_movie->setPaused(true);
    if (d->paused || !d->playing) {
        d->_movie->jumpToFrame(d->preset_currentframe);
        d->preset_currentframe = 0;
    }
    d->setImage(d->_movie->currentPixmap().toImage());

    if (isPlaying() != d->oldPlaying)
        emit playingChanged();
    if (sourceSize() != d->oldSourceSize) {
        d->oldSourceSize = sourceSize();
        emit sourceSizeChanged();
    }
}