Ejemplo n.º 1
1
void TagModificationHelper::slotTagDelete(TAlbum* t)
{
    if (!t || t->isRoot())
    {
        return;
    }

    AlbumPointer<TAlbum> tag(t);

    // find number of subtags
    int children = 0;
    AlbumIterator iter(tag);

    while (iter.current())
    {
        ++children;
        ++iter;
    }

    // ask for deletion of children
    if (children)
    {
        int result = KMessageBox::warningContinueCancel(d->dialogParent,
                                                        i18np("Tag '%2' has one subtag. "
                                                              "Deleting this will also delete "
                                                              "the subtag. "
                                                              "Do you want to continue?",
                                                              "Tag '%2' has %1 subtags. "
                                                              "Deleting this will also delete "
                                                              "the subtags. "
                                                              "Do you want to continue?",
                                                              children,
                                                              tag->title()));

        if (result != KMessageBox::Continue || !tag)
        {
            return;
        }
    }

    QString message;
    QList<qlonglong> assignedItems = DatabaseAccess().db()->getItemIDsInTag(tag->id());

    if (!assignedItems.isEmpty())
    {
        message = i18np("Tag '%2' is assigned to one item. "
                        "Do you want to continue?",
                        "Tag '%2' is assigned to %1 items. "
                        "Do you want to continue?",
                        assignedItems.count(), tag->title());
    }
    else
    {
        message = i18n("Delete '%1' tag?", tag->title());
    }

    int result = KMessageBox::warningContinueCancel(0, message,
                                                    i18n("Delete Tag"),
                                                    KGuiItem(i18n("Delete"),
                                                             "edit-delete"));

    if (result == KMessageBox::Continue && tag)
    {
        emit aboutToDeleteTag(tag);
        QString errMsg;

        if (!AlbumManager::instance()->deleteTAlbum(tag, errMsg))
        {
            KMessageBox::error(0, errMsg);
        }
    }
}
Ejemplo n.º 2
0
/**
 * Evento chamado quando o mouse é clicado
 */
void GraphicsScene::mousePressEvent(QGraphicsSceneMouseEvent *mouseEvent)
{
  if(!running)
  {
    QPointF pos = mouseEvent->scenePos(); //posição do mouse na hora do clique
    //qDebug() << "x: " << pos.x() << " y: " << pos.y();
    bool colidiu = false;
    QList<QGraphicsItem *> cidades = this->items(); //lista de cidades na tela

    if(mouseEvent->button() == Qt::LeftButton) //adicionar uma cidade
    {
        QRectF bboxCidade(pos.x(),pos.y(), cidadeWidth, cidadeHeigth); //bouding box da elipse da cidade

        //gradiente de cores de cada cidade
        QRadialGradient gradient(10, 10, 10, 10, 10);
        gradient.setColorAt(0, QColor::fromRgbF(0.5, 0.8, 0.7, 1));
        gradient.setColorAt(1, QColor::fromRgbF(0, 0, 0, 0));
        gradient.setSpread(QGradient::ReflectSpread);
        QBrush brush(gradient);

        QGraphicsEllipseItem *cidade = new QGraphicsEllipseItem(bboxCidade);
        cidade->setPen(QPen(Qt::black, 1, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));
        cidade->setBrush(brush);
        cidade->setZValue(1.0);

        for(int i = 0; i < cidades.size(); i++) //percorrendo a lista de cidades
        {
            if(cidades.at(i)->collidesWithItem(cidade) && cidades.at(i)->data(1).toBool())
            {
                colidiu = true;
                break;
            }
        }

        if(!colidiu) //se não houve colisão
        {
           cidade->setData(0, Cidade::getLastId() + 1);
           cidade->setData(1, 1);
           cidade->setData(4, pos);
           this->addItem(cidade);

           if(lastPos.x() != -10.0 && lastPos.y() != -10.0)
           {
               QPoint cids(Cidade::getLastId(),Cidade::getLastId() + 1);
               //this->drawEdge(lastPos, pos, cids);
           }

           lastPos = pos;
           emit cidadeCriada(pos); //sinal emitido quando uma cidade é criada
        }
    }
    else if(mouseEvent->button() == Qt::RightButton) //remover uma cidade
    {
        for(int i = 0; i < cidades.size(); i++) //percorrendo a lista de cidades
        {
            if(cidades.at(i)->contains(pos) && cidades.at(i)->data(1).toInt() == 1) //o mouse foi clicado em cima de uma cidade
            {
                int chave = cidades.at(i)->data(0).toInt();
                this->removeItem(cidades.at(i));
                //this->removeEdge(chave);

                if(items().size() == 0) lastPos = QPointF(-10,-10);
                emit cidadeRemovida(chave); //sinal emitido quando uma cidade removida
            }
        }
    }
  }
}
Ejemplo n.º 3
0
/*
 * Decompose CWallet transaction to model transaction records.
 */
QList<TransactionRecord> TransactionRecord::decomposeTransaction(const CWallet *wallet, const CWalletTx &wtx)
{
    QList<TransactionRecord> parts;
    int64_t nTime = wtx.GetTxTime();
    int64_t nCredit = wtx.GetCredit(true);
    int64_t nDebit = wtx.GetDebit();
    int64_t nNet = nCredit - nDebit;
    uint256 hash = wtx.GetHash(), hashPrev = 0;
    std::map<std::string, std::string> mapValue = wtx.mapValue;

    if (nNet > 0 || wtx.IsCoinBase() || wtx.IsCoinStake())
    {
        //
        // Credit
        //
        BOOST_FOREACH(const CTxOut& txout, wtx.vout)
        {
            if(wallet->IsMine(txout))
            {
                TransactionRecord sub(hash, nTime);
                CTxDestination address;
                sub.idx = parts.size(); // sequence number
                sub.credit = txout.nValue;
                if (ExtractDestination(txout.scriptPubKey, address) && IsMine(*wallet, address))
                {
                    // Received by Bitcoin Address
                    sub.type = TransactionRecord::RecvWithAddress;
                    sub.address = CBitcoinAddress(address).ToString();
                }
                else
                {
                    // Received by IP connection (deprecated features), or a multisignature or other non-simple transaction
                    sub.type = TransactionRecord::RecvFromOther;
                    sub.address = mapValue["from"];
                }
                if (wtx.IsCoinBase())
                {
                    // Generated (proof-of-work)
                    sub.type = TransactionRecord::Generated;
                }
                if (wtx.IsCoinStake())
                {
                    // Generated (proof-of-stake)

                    if (hashPrev == hash)
                        continue; // last coinstake output
                    int64_t nValueOut = 0;
                    BOOST_FOREACH(const CTxOut& txout, wtx.vout)
                    {
                        if (IsMine(*wallet,txout.scriptPubKey))
                            nValueOut += txout.nValue;
                        if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
                            throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
                    }
                    sub.type = TransactionRecord::Generated;
                    sub.credit = nNet > 0 ? nNet : nValueOut - nDebit;
                    hashPrev = hash;
                }

                parts.append(sub);
            }
        }
Ejemplo n.º 4
0
    MongoShellExecResult ScriptEngine::exec(const QString &originalScript, const QString &dbName)
    {
        QMutexLocker lock(&_mutex);

        /*
         * Replace all commands ('show dbs', 'use db' etc.) with call
         * to shellHelper('show', 'dbs') and so on.
         */
        QByteArray bytes = originalScript.toUtf8();
        std::string stdstr(bytes.constData(), bytes.size());

        pcrecpp::RE re("^(show|use|set) (\\w+)$",
            pcrecpp::RE_Options(PCRE_CASELESS|PCRE_MULTILINE|PCRE_NEWLINE_ANYCRLF));

        re.GlobalReplace("shellHelper('\\1', '\\2');", &stdstr);
        QString script = QString::fromUtf8(stdstr.c_str());

        /*
         * Statementize (i.e. extract all JavaScript statements from script) and
         * execute each statement one by one
         */
        QStringList statements;
        QString error;
        bool result = statementize(script, statements, error);

        if (!result && statements.count() == 0) {
            statements.append(QString("print(__robomongoResult.error)"));
        }

        QList<MongoShellResult> results;

        use(dbName);

        foreach(QString statement, statements)
        {
            // clear global objects
            __objects.clear();
            __type = "";
            __finished = false;
            __logs.str("");

            QByteArray array = statement.toUtf8();

            if (true /* ! wascmd */) {
                try {
                    QElapsedTimer timer;
                    timer.start();
                    if ( _scope->exec( array.data() , "(shell)" , false , true , false, 3600000 ) )
                        _scope->exec( "__robomongoLastRes = __lastres__; shellPrintHelper( __lastres__ );" , "(shell2)" , true , true , false, 3600000);

                    qint64 elapsed = timer.elapsed();

                    std::string logs = __logs.str();
                    QString answer = QString::fromUtf8(logs.c_str());
                    QString type = QString::fromUtf8(__type.c_str());

                    QVector<mongo::BSONObj> objs = QVector<mongo::BSONObj>::fromStdVector(__objects);
                    QList<mongo::BSONObj> list = QList<mongo::BSONObj>::fromVector(objs);
                    QList<MongoDocumentPtr> docs = MongoDocument::fromBsonObj(list);

                    if (!answer.isEmpty() || docs.count() > 0)
                        results.append(prepareResult(type, answer, docs, elapsed));
                }
                catch ( std::exception &e ) {
                    std::cout << "error:" << e.what() << endl;
                }
            }
        }
Ejemplo n.º 5
0
QList <Proceso *> ListaProcesos::getListaProcesosMet(DataZoneProject *dataZoPro)
{
    QList <Proceso *> listaProcesos;
    if(dataZoPro->getCoordinateSystem()==DataZoneProject::Etrs89)
    {
        if(dataZoPro->getAmbitoOperacion()==DataZoneProject::Catalunya)
        {
            listaProcesos.append(new ProcesoExtraction(this,_qMapEjecutables.value("exeExtraction")));
            listaProcesos.append(new ProcesoGeoTrans(this,_qMapEjecutables.value("exeGeoTransform")));
            listaProcesos.append(new ProcesoFootPrintMask(this,_qMapEjecutables.value("exeFootPrintMask")));
            listaProcesos.append(new ProcesoCutFiles(this,_qMapEjecutables.value("exeSubScene")));
        }
        if(dataZoPro->getAmbitoOperacion()==DataZoneProject::Espanya)
        {
            listaProcesos.append(new ProcesoSubScene(this,_qMapEjecutables.value("exeSubScene")));
            listaProcesos.append(new ProcesoResize(this,_qMapEjecutables.value("exeResize")));
            listaProcesos.append(new ProcesoFootPrintMask(this,_qMapEjecutables.value("exeFootPrintMask")));
            listaProcesos.append(new ProcesoCutFiles(this,_qMapEjecutables.value("exeSubScene")));
        }
    }
    if(dataZoPro->getCoordinateSystem()==DataZoneProject::Ed50)
    {
        if(dataZoPro->getAmbitoOperacion()==DataZoneProject::Catalunya)
        {
            if(dataZoPro->getFootPrintMask())
            {
                listaProcesos.append(new ProcesoExtraction(this,_qMapEjecutables.value("exeExtraction")));
                listaProcesos.append(new ProcesoFootPrintMask(this,_qMapEjecutables.value("exeFootPrintMask")));
                listaProcesos.append(new ProcesoGeoTrans(this,_qMapEjecutables.value("exeGeoTransform")));
                listaProcesos.append(new ProcesoCutFiles(this,_qMapEjecutables.value("exeSubScene")));
            }
            else
            {
                listaProcesos.append(new ProcesoExtraction(this,_qMapEjecutables.value("exeExtraction")));
                listaProcesos.append(new ProcesoGeoTrans(this,_qMapEjecutables.value("exeGeoTransform")));
                listaProcesos.append(new ProcesoFootPrintMask(this,_qMapEjecutables.value("exeFootPrintMask")));
                listaProcesos.append(new ProcesoCutFiles(this,_qMapEjecutables.value("exeSubScene")));
            }
        }
        if(dataZoPro->getAmbitoOperacion()==DataZoneProject::Espanya)
        {
            if(dataZoPro->getFootPrintMask())
            {
                listaProcesos.append(new ProcesoSubScene(this,_qMapEjecutables.value("exeSubScene")));
                listaProcesos.append(new ProcesoFootPrintMask(this,_qMapEjecutables.value("exeFootPrintMask")));
                listaProcesos.append(new ProcesoGeoTrans(this,_qMapEjecutables.value("exeGeoTransform")));
                listaProcesos.append(new ProcesoCutFiles(this,_qMapEjecutables.value("exeSubScene")));
            }
            else
            {
                listaProcesos.append(new ProcesoSubScene(this,_qMapEjecutables.value("exeSubScene")));
                listaProcesos.append(new ProcesoGeoTrans(this,_qMapEjecutables.value("exeGeoTransform")));
                listaProcesos.append(new ProcesoFootPrintMask(this,_qMapEjecutables.value("exeFootPrintMask")));
                listaProcesos.append(new ProcesoCutFiles(this,_qMapEjecutables.value("exeSubScene")));
            }
        }
    }
    if( dataZoPro->getCoordinateSystem()==DataZoneProject::Ntf)
    {
        listaProcesos.append(new ProcesoSubScene(this,_qMapEjecutables.value("exeSubScene")));
        listaProcesos.append(new ProcesoResize(this,_qMapEjecutables.value("exeResize")));
        listaProcesos.append(new ProcesoFootPrintMask(this,_qMapEjecutables.value("exeFootPrintMask")));
        listaProcesos.append(new ProcesoCutFiles(this,_qMapEjecutables.value("exeSubScene")));
    }
    return listaProcesos;
}
Ejemplo n.º 6
0
bool QAudioInputPrivate::open()
{
#ifdef DEBUG_AUDIO
    QTime now(QTime::currentTime());
    qDebug()<<now.second()<<"s "<<now.msec()<<"ms :open()";
#endif
    clockStamp.restart();
    timeStamp.restart();
    elapsedTimeOffset = 0;

    int dir;
    int err = 0;
    int count=0;
    unsigned int freakuency=settings.frequency();

    if (!settings.isValid()) {
        qWarning("QAudioOutput: open error, invalid format.");
    } else if (settings.sampleRate() <= 0) {
        qWarning("QAudioOutput: open error, invalid sample rate (%d).",
                 settings.sampleRate());
    } else {
        err = -1;
    }

    if (err == 0) {
        errorState = QAudio::OpenError;
        deviceState = QAudio::StoppedState;
        emit errorChanged(errorState);
        return false;
    }


    QString dev = QString(QLatin1String(m_device.constData()));
    QList<QByteArray> devices = QAudioDeviceInfoInternal::availableDevices(QAudio::AudioInput);
    if(dev.compare(QLatin1String("default")) == 0) {
#if(SND_LIB_MAJOR == 1 && SND_LIB_MINOR == 0 && SND_LIB_SUBMINOR >= 14)
        if (devices.size() > 0)
            dev = QLatin1String(devices.first());
        else
            return false;
#else
        dev = QLatin1String("hw:0,0");
#endif
    } else {
#if(SND_LIB_MAJOR == 1 && SND_LIB_MINOR == 0 && SND_LIB_SUBMINOR >= 14)
        dev = QLatin1String(m_device);
#else
        int idx = 0;
        char *name;

        QString shortName = QLatin1String(m_device.mid(m_device.indexOf('=',0)+1).constData());

        while(snd_card_get_name(idx,&name) == 0) {
            if(qstrncmp(shortName.toLocal8Bit().constData(),name,shortName.length()) == 0)
                break;
            idx++;
        }
        dev = QString(QLatin1String("hw:%1,0")).arg(idx);
#endif
    }

    // Step 1: try and open the device
    while((count < 5) && (err < 0)) {
        err=snd_pcm_open(&handle,dev.toLocal8Bit().constData(),SND_PCM_STREAM_CAPTURE,0);
        if(err < 0)
            count++;
    }
    if (( err < 0)||(handle == 0)) {
        errorState = QAudio::OpenError;
        deviceState = QAudio::StoppedState;
        emit stateChanged(deviceState);
        return false;
    }
    snd_pcm_nonblock( handle, 0 );

    // Step 2: Set the desired HW parameters.
    snd_pcm_hw_params_alloca( &hwparams );

    bool fatal = false;
    QString errMessage;
    unsigned int chunks = 8;

    err = snd_pcm_hw_params_any( handle, hwparams );
    if ( err < 0 ) {
        fatal = true;
        errMessage = QString::fromLatin1("QAudioInput: snd_pcm_hw_params_any: err = %1").arg(err);
    }
    if ( !fatal ) {
        err = snd_pcm_hw_params_set_rate_resample( handle, hwparams, 1 );
        if ( err < 0 ) {
            fatal = true;
            errMessage = QString::fromLatin1("QAudioInput: snd_pcm_hw_params_set_rate_resample: err = %1").arg(err);
        }
    }
    if ( !fatal ) {
        err = snd_pcm_hw_params_set_access( handle, hwparams, access );
        if ( err < 0 ) {
            fatal = true;
            errMessage = QString::fromLatin1("QAudioInput: snd_pcm_hw_params_set_access: err = %1").arg(err);
        }
    }
    if ( !fatal ) {
        err = setFormat();
        if ( err < 0 ) {
            fatal = true;
            errMessage = QString::fromLatin1("QAudioInput: snd_pcm_hw_params_set_format: err = %1").arg(err);
        }
    }
    if ( !fatal ) {
        err = snd_pcm_hw_params_set_channels( handle, hwparams, (unsigned int)settings.channels() );
        if ( err < 0 ) {
            fatal = true;
            errMessage = QString::fromLatin1("QAudioInput: snd_pcm_hw_params_set_channels: err = %1").arg(err);
        }
    }
    if ( !fatal ) {
        err = snd_pcm_hw_params_set_rate_near( handle, hwparams, &freakuency, 0 );
        if ( err < 0 ) {
            fatal = true;
            errMessage = QString::fromLatin1("QAudioInput: snd_pcm_hw_params_set_rate_near: err = %1").arg(err);
        }
    }
    if ( !fatal ) {
        err = snd_pcm_hw_params_set_buffer_time_near(handle, hwparams, &buffer_time, &dir);
        if ( err < 0 ) {
            fatal = true;
            errMessage = QString::fromLatin1("QAudioInput: snd_pcm_hw_params_set_buffer_time_near: err = %1").arg(err);
        }
    }
    if ( !fatal ) {
        err = snd_pcm_hw_params_set_period_time_near(handle, hwparams, &period_time, &dir);
        if ( err < 0 ) {
            fatal = true;
            errMessage = QString::fromLatin1("QAudioInput: snd_pcm_hw_params_set_period_time_near: err = %1").arg(err);
        }
    }
    if ( !fatal ) {
        err = snd_pcm_hw_params_set_periods_near(handle, hwparams, &chunks, &dir);
        if ( err < 0 ) {
            fatal = true;
            errMessage = QString::fromLatin1("QAudioInput: snd_pcm_hw_params_set_periods_near: err = %1").arg(err);
        }
    }
    if ( !fatal ) {
        err = snd_pcm_hw_params(handle, hwparams);
        if ( err < 0 ) {
            fatal = true;
            errMessage = QString::fromLatin1("QAudioInput: snd_pcm_hw_params: err = %1").arg(err);
        }
    }
    if( err < 0) {
        qWarning()<<errMessage;
        errorState = QAudio::OpenError;
        deviceState = QAudio::StoppedState;
        emit stateChanged(deviceState);
        return false;
    }
    snd_pcm_hw_params_get_buffer_size(hwparams,&buffer_frames);
    buffer_size = snd_pcm_frames_to_bytes(handle,buffer_frames);
    snd_pcm_hw_params_get_period_size(hwparams,&period_frames, &dir);
    period_size = snd_pcm_frames_to_bytes(handle,period_frames);
    snd_pcm_hw_params_get_buffer_time(hwparams,&buffer_time, &dir);
    snd_pcm_hw_params_get_period_time(hwparams,&period_time, &dir);

    // Step 3: Set the desired SW parameters.
    snd_pcm_sw_params_t *swparams;
    snd_pcm_sw_params_alloca(&swparams);
    snd_pcm_sw_params_current(handle, swparams);
    snd_pcm_sw_params_set_start_threshold(handle,swparams,period_frames);
    snd_pcm_sw_params_set_stop_threshold(handle,swparams,buffer_frames);
    snd_pcm_sw_params_set_avail_min(handle, swparams,period_frames);
    snd_pcm_sw_params(handle, swparams);

    // Step 4: Prepare audio
    ringBuffer.resize(buffer_size);
    snd_pcm_prepare( handle );
    snd_pcm_start(handle);

    // Step 5: Setup timer
    bytesAvailable = checkBytesReady();

    if(pullMode)
        connect(audioSource,SIGNAL(readyRead()),this,SLOT(userFeed()));

    // Step 6: Start audio processing
    chunks = buffer_size/period_size;
    timer->start(period_time*chunks/2000);

    errorState  = QAudio::NoError;

    totalTimeValue = 0;

    return true;
}
Ejemplo n.º 7
0
void reprintInvoices::sPrint()
{
  QPrinter printer(QPrinter::HighResolution);
  bool     setupPrinter = TRUE;

  bool userCanceled = false;
  if (orReport::beginMultiPrint(&printer, userCanceled) == false)
  {
    if(!userCanceled)
      systemError(this, tr("Could not initialize printing system for multiple reports."));
    return;
  }
  QList<QTreeWidgetItem*> selected = _invoice->selectedItems();
  for (int i = 0; i < selected.size(); i++)
  {
    XTreeWidgetItem *cursor = (XTreeWidgetItem*)selected[i];

    for (int j = 0; j < _watermarks->topLevelItemCount(); j++)
    {
      q.prepare("SELECT findCustomerForm(:cust_id, 'I') AS _reportname;");
      q.bindValue(":cust_id", cursor->altId());
      q.exec();
      if (q.first())
      {
	ParameterList params;
	params.append("invchead_id", cursor->id());
	params.append("showcosts", ((_watermarks->topLevelItem(j)->text(2) == tr("Yes")) ? "TRUE" : "FALSE") );
	params.append("watermark", _watermarks->topLevelItem(j)->text(1));

	orReport report(q.value("_reportname").toString(), params);
	if (report.isValid())
	{
	  if (report.print(&printer, setupPrinter))
		 setupPrinter = FALSE;
	      else 
	      {
		report.reportError(this);
		orReport::endMultiPrint(&printer);
		return;
	      }
	}
	else
	  QMessageBox::critical( this, tr("Cannot Find Invoice Form"),
				 tr( "The Invoice Form '%1' cannot be found.\n"
				     "One or more of the selected Invoices cannot be printed until a Customer Form Assignment\n"
				     "is updated to remove any references to this Invoice Form or this Invoice Form is created." )
				 .arg(q.value("_reportname").toString()) );
      }
      else if (q.lastError().type() != QSqlError::None)
      {
	systemError(this, q.lastError().databaseText(), __FILE__, __LINE__);
	return;
      }
    }
    if (_metrics->boolean("EnableBatchManager"))
    {
      // TODO: Check for EDI and handle submission to Batch here
      q.prepare("SELECT CASE WHEN (COALESCE(shipto_ediprofile_id, -2) = -2)"
	      "              THEN COALESCE(cust_ediprofile_id,-1)"
	      "            ELSE COALESCE(shipto_ediprofile_id,-2)"
	      "       END AS result,"
	      "       COALESCE(cust_emaildelivery, false) AS custom"
	      "  FROM cust, invchead"
	      "       LEFT OUTER JOIN shipto"
	      "         ON (invchead_shipto_id=shipto_id)"
	      "  WHERE ((invchead_cust_id=cust_id)"
	      "    AND  (invchead_id=:invchead_id)); ");
      q.bindValue(":invchead_id", cursor->id());
      q.exec();
      if(q.first())
      {
	if(q.value("result").toInt() == -1)
	{
	  if(q.value("custom").toBool())
	  {
	    ParameterList params;
	    params.append("invchead_id", cursor->id());
  
	    deliverInvoice newdlg(this, "", TRUE);
	    newdlg.set(params);
	    newdlg.exec();
	  }
	}
	else
	{
	  ParameterList params;
	  params.append("action_name", "TransmitInvoice");
	  params.append("invchead_id", cursor->id());
  
	  submitAction newdlg(this, "", TRUE);
	  newdlg.set(params);
	  newdlg.exec();
	}
      }
    }
    else if (q.lastError().type() != QSqlError::None)
    {
      systemError(this, q.lastError().databaseText(), __FILE__, __LINE__);
      return;
    }
  }
  orReport::endMultiPrint(&printer);

  _invoice->clearSelection();
  _close->setText(tr("&Close"));
  _print->setEnabled(FALSE);
}
Ejemplo n.º 8
0
void PictureLoader::processLoadQueue()
{
    if (loadQueueRunning)
        return;

    loadQueueRunning = true;
    forever {
        mutex.lock();
        if (loadQueue.isEmpty()) {
            mutex.unlock();
            loadQueueRunning = false;
            return;
        }
        PictureToLoad ptl = loadQueue.takeFirst();
        mutex.unlock();

        //The list of paths to the folders in which to search for images
        QList<QString> picsPaths = QList<QString>() << _picsPath + "/CUSTOM/" + ptl.getCard()->getCorrectedName();


        QString setName=ptl.getSetName();
        if(!setName.isEmpty())
        {
            picsPaths   << _picsPath + "/" + setName + "/" + ptl.getCard()->getCorrectedName()
                        << _picsPath + "/downloadedPics/" + setName + "/" + ptl.getCard()->getCorrectedName();
        }

        QImage image;
        QImageReader imgReader;
        imgReader.setDecideFormatFromContent(true);
        bool found = false;

        //Iterates through the list of paths, searching for images with the desired name with any QImageReader-supported extension
        for (int i = 0; i < picsPaths.length() && !found; i ++) {
            imgReader.setFileName(picsPaths.at(i));
            if (imgReader.read(&image)) {
                emit imageLoaded(ptl.getCard(), image);
                found = true;
                break;
            }
            imgReader.setFileName(picsPaths.at(i) + ".full");
            if (imgReader.read(&image)) {
                emit imageLoaded(ptl.getCard(), image);
                found = true;
            }
        }

        if (!found) {
            if (picDownload) {
                cardsToDownload.append(ptl);
                if (!downloadRunning)
                    startNextPicDownload();
            } else {
                if (ptl.nextSet())
                    loadQueue.prepend(ptl);
                else
                    emit imageLoaded(ptl.getCard(), QImage());
            }
        }
    }
}
Ejemplo n.º 9
0
void TagModificationHelper::slotMultipleTagDel()
{
    QList<TAlbum*> lst = boundMultipleTags(sender());
    kDebug() << lst.size();
    slotMultipleTagDel(lst);
}
Ejemplo n.º 10
0
void TagModificationHelper::slotMultipleTagDel(QList<TAlbum* >& tags)
{
    QString tagWithChildrens;
    QString tagWithImages;
    QMultiMap<int, TAlbum*> sortedTags;

    foreach(TAlbum* const t, tags)
    {

        if (!t || t->isRoot())
        {
            continue;
        }

        AlbumPointer<TAlbum> tag(t);

        // find number of subtags
        int children = 0;
        AlbumIterator iter(tag);

        while (iter.current())
        {
            ++children;
            ++iter;
        }

        if(children)
            tagWithChildrens.append(tag->title() + QString(" "));

        QList<qlonglong> assignedItems = DatabaseAccess().db()->getItemIDsInTag(tag->id());

        if(!assignedItems.isEmpty())
            tagWithImages.append(tag->title() + QString(" "));

        /**
         * Tags must be deleted from children to parents, if we don't want
         * to step on invalid index. Use QMultiMap to order them by distance
         * to root tag
         */

        Album* parent = t;
        int depth = 0;

        while(!parent->isRoot())
        {
            parent = parent->parent();
            depth++;
        }

        sortedTags.insert(depth,tag);

    }

    // ask for deletion of children

    if (!tagWithChildrens.isEmpty())
    {
        int result = KMessageBox::warningContinueCancel(0,
                                                        i18n("Tags '%1' have one or more subtags. "
                                                             "Deleting them will also delete "
                                                             "the subtags. "
                                                             "Do you want to continue?",
                                                             tagWithChildrens));

        if (result != KMessageBox::Continue)
        {
            return;
        }
    }

    QString message;

    if (!tagWithImages.isEmpty())
    {
        message = i18n("Tags '%1' are assigned to one or more items. "
                        "Do you want to continue?",
                        tagWithImages);
    }
    else
    {
        message = i18n("Delete '%1' tag(s)?", tagWithImages);
    }

    int result = KMessageBox::warningContinueCancel(0, message,
                                                    i18n("Delete Tag"),
                                                    KGuiItem(i18n("Delete"),
                                                            "edit-delete"));

    if (result == KMessageBox::Continue)
    {
        QMultiMap<int, TAlbum*>::iterator it;
        /**
         * QMultimap doesn't provide reverse iterator, -1 is required
         * because end() points after the last element
         */
        for(it = sortedTags.end()-1; it != sortedTags.begin()-1; --it)
        {
            emit aboutToDeleteTag(it.value());
            QString errMsg;

            if (!AlbumManager::instance()->deleteTAlbum(it.value(), errMsg))
            {
                KMessageBox::error(0, errMsg);
            }
        }
    }
}
Ejemplo n.º 11
0
void GameRule::onPhaseChange(ServerPlayer *player) const {
    Room *room = player->getRoom();
    switch(player->getPhase()) {
    case Player::Start: {
        player->setMark("SlashCount", 0);
        break;
    }
    case Player::Judge: {
        QList<const DelayedTrick *> tricks = player->delayedTricks();
        while(!tricks.isEmpty() && player->isAlive()) {
            const DelayedTrick *trick = tricks.takeLast();
            bool on_effect = room->cardEffect(trick, NULL, player);
            if(!on_effect)
                trick->onNullified(player);
        }

        break;
    }
    case Player::Draw: {
        QVariant num = 2;
        if(room->getTag("FirstRound").toBool() && room->getMode() == "02_1v1") {
            room->setTag("FirstRound", false);
            num = 1;
        }

        room->getThread()->trigger(DrawNCards, player, num);
        int n = num.toInt();
        if(n > 0)
            player->drawCards(n, false);
        break;
    }

    case Player::Play: {
        player->clearHistory();

        while(player->isAlive()) {
            CardUseStruct card_use;
            room->activate(player, card_use);
            if(card_use.isValid()) {
                room->useCard(card_use);
            } else
                break;
        }
        break;
    }

    case Player::Discard: {
        int discard_num = player->getHandcardNum() - player->getMaxCards();
        if(player->hasFlag("jilei")) {
            QSet<const Card *> jilei_cards;
            QList<const Card *> handcards = player->getHandcards();
            foreach(const Card *card, handcards) {
                if(player->isJilei(card))
                    jilei_cards << card;
            }

            if(jilei_cards.size() > player->getMaxCards()) {
                // show all his cards
                room->showAllCards(player);

                foreach(const Card *card, handcards.toSet() - jilei_cards) {
                    room->throwCard(card);
                }

                return;
            }
        }

        if(discard_num > 0)
            room->askForDiscard(player, "gamerule", discard_num);
        break;
    }
Ejemplo n.º 12
0
bool OneCardViewAsSkill::viewFilter(const QList<CardItem *> &selected, const CardItem *to_select) const{
    return selected.isEmpty() && viewFilter(to_select);
}
Ejemplo n.º 13
0
Value* ComplexValue::operation(Value& v, Expression::Operator_e op)
{
	auto* c=dynamic_cast<ComplexValue*>(&v);
	if(c) {
		if(imaginary.size()>2&&c->imaginary.size()>2) {
			Value* w1=real;
			Value* w2=c->real;

			Value* x1=imaginary.at(0);
			Value* x2=c->imaginary.at(0);

			Value* y1=imaginary.at(1);
			Value* y2=c->imaginary.at(1);

			Value* z1=imaginary.at(2);
			Value* z2=c->imaginary.at(2);

			if(op==Expression::Multiply) {
				//(Q1 * Q2).w = (w1w2 - x1x2 - y1y2 - z1z2)
				//(Q1 * Q2).x = (w1x2 + x1w2 + y1z2 - z1y2)
				//(Q1 * Q2).y = (w1y2 - x1z2 + y1w2 + z1x2)
				//(Q1 * Q2).z = (w1z2 + x1y2 - y1x2 + z1w2)
				Value *w,*x,*y,*z;
				Value* w1w2 = Value::operation(w1,op,w2);
				Value* x1x2 = Value::operation(x1,op,x2);
				Value* y1y2 = Value::operation(y1,op,y2);
				Value* z1z2 = Value::operation(z1,op,z2);
				w = Value::operation(w1w2,Expression::Subtract,x1x2);
				w = Value::operation(w,Expression::Subtract,y1y2);
				w = Value::operation(w,Expression::Subtract,z1z2);

				Value* w1x2 = Value::operation(w1,op,x2);
				Value* x1w2 = Value::operation(x1,op,w2);
				Value* y1z2 = Value::operation(y1,op,z2);
				Value* z1y2 = Value::operation(z1,op,y2);
				x = Value::operation(w1x2,Expression::Add,x1w2);
				x = Value::operation(x,Expression::Add,y1z2);
				x = Value::operation(x,Expression::Subtract,z1y2);

				Value* w1y2 = Value::operation(w1,op,y2);
				Value* x1z2 = Value::operation(x1,op,z2);
				Value* y1w2 = Value::operation(y1,op,w2);
				Value* z1x2 = Value::operation(z1,op,x2);
				y = Value::operation(w1y2,Expression::Subtract,x1z2);
				y = Value::operation(y,Expression::Add,y1w2);
				y = Value::operation(y,Expression::Add,z1x2);

				Value* w1z2 = Value::operation(w1,op,z2);
				Value* x1y2 = Value::operation(x1,op,y2);
				Value* y1x2 = Value::operation(y1,op,x2);
				Value* z1w2 = Value::operation(z1,op,w2);
				z = Value::operation(w1z2,Expression::Subtract,x1y2);
				z = Value::operation(z,Expression::Add,y1x2);
				z = Value::operation(z,Expression::Add,z1w2);

				QList<Value*> i;
				i.append(x);
				i.append(y);
				i.append(z);

				return new ComplexValue(w,i);
			} else if(op==Expression::Equal||op==Expression::NotEqual) {
				Value* eqRe=Value::operation(real,op,c->real);
				bool eq=eqRe->isTrue();
				if(op==Expression::NotEqual && !eq)
					return new BooleanValue(true);
				if(eq)
					for(auto i=0; i<3; ++i) {
						Value* eqIm=Value::operation(imaginary.at(i),op,c->imaginary.at(i));
						if(op==Expression::NotEqual && eqIm->isTrue())
							return new BooleanValue(true);
						if(eqIm->isFalse())
							eq=false;
					}
				return new BooleanValue(eq);
			}
		}
	}

	auto* n=dynamic_cast<NumberValue*>(&v);
	if(n) {
		if(op==Expression::Divide) {
			Value* w=Value::operation(real,Expression::Divide,n);
			QList<Value*> result;
			for(Value* i: imaginary) {
				Value* a=Value::operation(i,Expression::Divide,n);
				result.append(a);
			}
			return new ComplexValue(w,result);
		}
	}

	return Value::undefined();
}
Ejemplo n.º 14
0
void QXmppDataForm::parse(const QDomElement &element)
{
    if (element.isNull())
        return;

    /* form type */
    const QString typeStr = element.attribute("type");
    if (typeStr == "form")
        m_type = QXmppDataForm::Form;
    else if (typeStr == "submit")
        m_type = QXmppDataForm::Submit;
    else if (typeStr == "cancel")
        m_type = QXmppDataForm::Cancel;
    else if (typeStr == "result")
        m_type = QXmppDataForm::Result;
    else
    {
        qWarning() << "Unknown form type" << typeStr;
        return;
    }

    /* form properties */
    m_title = element.firstChildElement("title").text();
    m_instructions = element.firstChildElement("instructions").text();

    QDomElement fieldElement = element.firstChildElement("field");
    while (!fieldElement.isNull())
    {
        QXmppDataForm::Field field;

        /* field type */
        QXmppDataForm::Field::Type type = static_cast<QXmppDataForm::Field::Type>(-1);
        const QString typeStr = fieldElement.attribute("type");
        struct field_type *ptr;
        for (ptr = field_types; ptr->str; ptr++)
        {
            if (typeStr == ptr->str)
            {
                type = ptr->type;
                break;
            }
        }
        if (type < 0)
            qWarning() << "Unknown field type" << typeStr;
        field.setType(type);

        /* field attributes */
        field.setLabel(fieldElement.attribute("label"));
        field.setKey(fieldElement.attribute("var"));

        /* field value(s) */
        if (type == QXmppDataForm::Field::BooleanField)
        {
            const QString valueStr = fieldElement.firstChildElement("value").text();
            field.setValue(valueStr == "1" || valueStr == "true");
        }
        else if (type == QXmppDataForm::Field::ListMultiField ||
            type == QXmppDataForm::Field::JidMultiField || 
            type == QXmppDataForm::Field::TextMultiField) 
        {
            QStringList values;
            QDomElement valueElement = fieldElement.firstChildElement("value");
            while (!valueElement.isNull())
            {
                values.append(valueElement.text());
                valueElement = valueElement.nextSiblingElement("value");
            }
            field.setValue(values);
        }
        else
        {
            field.setValue(fieldElement.firstChildElement("value").text());
        }

        /* field options */
        if (type == QXmppDataForm::Field::ListMultiField ||
            type == QXmppDataForm::Field::ListSingleField)
        { 
            QList<QPair<QString, QString> > options;
            QDomElement optionElement = fieldElement.firstChildElement("option");
            while (!optionElement.isNull())
            {
                options.append(QPair<QString, QString>(optionElement.attribute("label"),
                    optionElement.firstChildElement("value").text()));
                optionElement = optionElement.nextSiblingElement("option"); 
            }
            field.setOptions(options);
        }

        /* other properties */
        field.setDescription(fieldElement.firstChildElement("description").text());
        field.setRequired(!fieldElement.firstChildElement("required").isNull());

        m_fields.append(field);

        fieldElement = fieldElement.nextSiblingElement("field");
    }
}
Ejemplo n.º 15
0
void AssimpLoader::parseMeshes(aiMesh **meshes,
    const unsigned int numMeshes, QList<PolygonalDrawable *> &drawables) const
{
    for (unsigned int i = 0; i < numMeshes; i++)
        drawables.insert(i, parseMesh(*meshes[i]));
}
Ejemplo n.º 16
0
void MesytecMadc32UI::applySettings()
{
    applyingSettings = true;

    QList<QGroupBox*> gbs = findChildren<QGroupBox*>();
    if(!gbs.empty())
    {
        QList<QGroupBox*>::const_iterator it = gbs.begin();
        while(it != gbs.end())
        {
            QGroupBox* w = (*it);
            for(int ch=0; ch < MADC32V2_NUM_CHANNELS; ch++) {
                if(w->objectName() == tr("enable_channel%1").arg(ch)) w->setChecked(module->conf_.enable_channel[ch]);
            }
            it++;
        }
    }
    QList<QCheckBox*> cbs = findChildren<QCheckBox*>();
    if(!cbs.empty())
    {
        QList<QCheckBox*>::const_iterator it = cbs.begin();
        while(it != cbs.end())
        {
            QCheckBox* w = (*it);

            if(w->objectName() == "enable_multi_event_send_different_eob_marker") w->setChecked(module->conf_.enable_multi_event_send_different_eob_marker);
            if(w->objectName() == "enable_multi_event_compare_with_max_transfer_data") w->setChecked(module->conf_.enable_multi_event_compare_with_max_transfer_data);
            if(w->objectName() == "enable_adc_override") w->setChecked(module->conf_.enable_adc_override);
            if(w->objectName() == "enable_switch_off_sliding_scale") w->setChecked(module->conf_.enable_switch_off_sliding_scale);
            if(w->objectName() == "enable_skip_out_of_range") w->setChecked(module->conf_.enable_skip_out_of_range);
            if(w->objectName() == "enable_ignore_thresholds") w->setChecked(module->conf_.enable_ignore_thresholds);
            if(w->objectName() == "enable_termination_input_gate0") w->setChecked(module->conf_.enable_termination_input_gate0);
            if(w->objectName() == "enable_termination_input_fast_clear") w->setChecked(module->conf_.enable_termination_input_fast_clear);
            if(w->objectName() == "enable_external_time_stamp_reset") w->setChecked(module->conf_.enable_external_time_stamp_reset);

            it++;
        }
    }
    QList<QComboBox*> cbbs = findChildren<QComboBox*>();
    if(!cbbs.empty())
    {
        QList<QComboBox*>::const_iterator it = cbbs.begin();
        while(it != cbbs.end())
        {
            QComboBox* w = (*it);
            //printf("Found combobox with the name %s\n",w->objectName().toStdString().c_str());
            if(w->objectName() == "addr_source") w->setCurrentIndex(module->conf_.addr_source);
            if(w->objectName() == "multi_event_mode") w->setCurrentIndex(module->conf_.multi_event_mode);
            if(w->objectName() == "vme_mode") w->setCurrentIndex(module->conf_.vme_mode);
            if(w->objectName() == "data_length_format") w->setCurrentIndex(module->conf_.data_length_format);
            if(w->objectName() == "time_stamp_source") w->setCurrentIndex(module->conf_.time_stamp_source);
            if(w->objectName() == "adc_resolution") w->setCurrentIndex(module->conf_.adc_resolution);
            if(w->objectName() == "output_format") w->setCurrentIndex(module->conf_.output_format);
            if(w->objectName() == "gate_generator_mode") w->setCurrentIndex(module->conf_.gate_generator_mode);
            if(w->objectName() == "ecl_gate1_mode") w->setCurrentIndex(module->conf_.ecl_gate1_mode);
            if(w->objectName() == "ecl_fclear_mode") w->setCurrentIndex(module->conf_.ecl_fclear_mode);
            if(w->objectName() == "ecl_busy_mode") w->setCurrentIndex(module->conf_.ecl_busy_mode);
            if(w->objectName() == "nim_gate1_mode") w->setCurrentIndex(module->conf_.nim_gate1_mode);
            if(w->objectName() == "nim_fclear_mode") w->setCurrentIndex(module->conf_.nim_fclear_mode);
            if(w->objectName() == "input_range") {
                switch (module->conf_.input_range){
                case MesytecMadc32ModuleConfig::ir4V: w->setCurrentIndex(0); break;
                case MesytecMadc32ModuleConfig::ir8V: w->setCurrentIndex(1); break;
                case MesytecMadc32ModuleConfig::ir10V: w->setCurrentIndex(2); break;
                default: w->setCurrentIndex(2); break;
                }
            }
            if(w->objectName() == "marking_type") w->setCurrentIndex(module->conf_.marking_type);
            if(w->objectName() == "bank_operation") w->setCurrentIndex(module->conf_.bank_operation);
            if(w->objectName() == "test_pulser_mode") w->setCurrentIndex(module->conf_.test_pulser_mode);
            it++;
        }
    }
    QList<QSpinBox*> csb = findChildren<QSpinBox*>();
    if(!csb.empty())
    {
        QList<QSpinBox*>::const_iterator it = csb.begin();
        while(it != csb.end())
        {
            QSpinBox* w = (*it);
            //printf("Found spinbox with the name %s\n",w->objectName().toStdString().c_str());
            if(w->objectName() == "irq_level") w->setValue(module->conf_.irq_level);
            if(w->objectName() == "irq_vector") w->setValue(module->conf_.irq_vector);
            if(w->objectName() == "irq_threshold") w->setValue(module->conf_.irq_threshold);
            if(w->objectName() == "base_addr_register") w->setValue(module->conf_.base_addr_register);
            if(w->objectName() == "time_stamp_divisor") w->setValue(module->conf_.time_stamp_divisor);
            if(w->objectName() == "max_transfer_data") w->setValue(module->conf_.max_transfer_data);
            if(w->objectName() == "rc_module_id_read") w->setValue(module->conf_.rc_module_id_read);
            if(w->objectName() == "rc_module_id_write") w->setValue(module->conf_.rc_module_id_write);

            for(int ch=0; ch<2; ch++)
            {
                if(w->objectName() == tr("hold_delay_%1").arg(ch)) w->setValue(module->conf_.hold_delay[ch]);
                if(w->objectName() == tr("hold_width_%1").arg(ch)) w->setValue(module->conf_.hold_width[ch]);
            }
            for(int ch=0; ch<MADC32V2_NUM_CHANNELS; ch++)
            {
                if(w->objectName() == tr("thresholds%1").arg(ch)) w->setValue(module->conf_.thresholds[ch]);
            }
            it++;
        }
    }
    QList<QRadioButton*> crb = findChildren<QRadioButton*>();
    if(!crb.empty())
    {
        QList<QRadioButton*>::const_iterator it = crb.begin();
        while(it != crb.end())
        {
            QRadioButton* w = (*it);
            if(w->objectName() == "mcst_cblt_none") w->setChecked(module->conf_.mcst_cblt_none);
            if(w->objectName() == "enable_cblt_mode") w->setChecked(module->conf_.enable_cblt_mode);
            if(w->objectName() == "enable_mcst_mode") w->setChecked(module->conf_.enable_mcst_mode);
            if(w->objectName() == "enable_cblt_first") w->setChecked(module->conf_.enable_cblt_first);
            if(w->objectName() == "enable_cblt_last") w->setChecked(module->conf_.enable_cblt_last);
            if(w->objectName() == "enable_cblt_middle") w->setChecked(module->conf_.enable_cblt_middle);
            it++;
        }
    }
\
    QLabel* b_addr = (QLabel*) uif.getWidgets()->find("base_addr").value();
    b_addr->setText(tr("0x%1").arg(module->conf_.base_addr,2,16,QChar('0')));

    applyingSettings = false;
}
Ejemplo n.º 17
0
/** Upgrade from <= 1.7 library to 1.8 DB format */
void LegacyLibraryImporter::import() {
    // Here we need the SETTINGS_PATH from Mixxx V <= 1.7
    QString settingPath17 = Upgrade::mixxx17HomePath();

    QString trackXML = settingPath17.append("mixxxtrack.xml");
    QFile file(trackXML);

    QDomDocument doc("TrackList");

    if(!file.open(QIODevice::ReadOnly)) {
        //qDebug() << "Could not import legacy 1.7 XML library: " << trackXML;
        return;
    }

    QString* errorMsg = NULL;
    int* errorLine = NULL;
    int* errorColumn = NULL;

    qDebug() << "Starting upgrade from 1.7 library...";

    QHash<int, QString> playlistHashTable; // Maps track indices onto track locations
    QList<LegacyPlaylist> legacyPlaylists; // <= 1.7 playlists

    if (doc.setContent(&file, false, errorMsg, errorLine, errorColumn)) {

        QDomNodeList playlistList = doc.elementsByTagName("Playlist");
        QDomNode playlist;
        for (int i = 0; i < playlistList.size(); i++) {
            LegacyPlaylist legPlaylist;
            playlist = playlistList.at(i);

            QString name = playlist.firstChildElement("Name").text();

            legPlaylist.name = name;

            // Store the IDs in the hash table so we can map them to track locations later,
            // and also store them in-order in a temporary playlist struct.
            QDomElement listNode = playlist.firstChildElement("List").toElement();
            QDomNodeList trackIDs = listNode.elementsByTagName("Id");
            for (int j = 0; j < trackIDs.size(); j++) {
                int id = trackIDs.at(j).toElement().text().toInt();
                if (!playlistHashTable.contains(id))
                    playlistHashTable.insert(id, "");
                legPlaylist.indexes.push_back(id); // Save this track id.
            }
            // Save this playlist in our list.
            legacyPlaylists.push_back(legPlaylist);
        }

        QDomNodeList trackList = doc.elementsByTagName("Track");
        QDomNode track;

        for (int i = 0; i < trackList.size(); i++) {
            // blah, can't figure out how to use an iterator with QDomNodeList
            track = trackList.at(i);
            TrackInfoObject trackInfo17(track);
            // Only add the track to the DB if the file exists on disk,
            // because Mixxx <= 1.7 had no logic to deal with detecting deleted
            // files.

            if (trackInfo17.exists()) {
                // Create a TrackInfoObject by directly parsing
                // the actual MP3/OGG/whatever because 1.7 didn't parse
                // genre and album tags (so the imported TIO doesn't have
                // those fields).
                emit(progress("Upgrading Mixxx 1.7 Library: " + trackInfo17.getTitle()));

                // Read the metadata we couldn't support in <1.8 from file.
                QFileInfo fileInfo(trackInfo17.getLocation());
                // Ensure we have the absolute file path stored
                trackInfo17.setLocation(fileInfo.absoluteFilePath());
                TrackInfoObject trackInfoNew(trackInfo17.getLocation());
                trackInfo17.setGenre(trackInfoNew.getGenre());
                trackInfo17.setAlbum(trackInfoNew.getAlbum());
                trackInfo17.setYear(trackInfoNew.getYear());
                trackInfo17.setType(trackInfoNew.getType());
                trackInfo17.setTrackNumber(trackInfoNew.getTrackNumber());
                trackInfo17.setKeys(trackInfoNew.getKeys());
                trackInfo17.setHeaderParsed(true);

                // Import the track's saved cue point if it is non-zero.
                float fCuePoint = trackInfo17.getCuePoint();
                if (fCuePoint != 0.0f) {
                    Cue* pCue = trackInfo17.addCue();
                    pCue->setType(Cue::CUE);
                    pCue->setPosition(fCuePoint);
                }

                // Provide a no-op deleter b/c this Track is on the stack.
                TrackPointer pTrack(&trackInfo17, &doNothing);
                m_trackDao.saveTrack(pTrack);

                // Check if this track is used in a playlist anywhere. If it is, save the
                // track location. (The "id" of a track in 1.8 is a database index, so it's totally
                // different. Using the track location is the best way for us to identify the song.)
                int id = trackInfo17.getId();
                if (playlistHashTable.contains(id))
                    playlistHashTable[id] = trackInfo17.getLocation();
            }
        }


        // Create the imported playlists
        QListIterator<LegacyPlaylist> it(legacyPlaylists);
        LegacyPlaylist current;
        while (it.hasNext()) {
            current = it.next();
            emit(progress("Upgrading Mixxx 1.7 Playlists: " + current.name));

            // Create the playlist with the imported name.
            //qDebug() << "Importing playlist:" << current.name;
            int playlistId = m_playlistDao.createPlaylist(current.name);

            // For each track ID in the XML...
            QList<int> trackIDs = current.indexes;
            for (int i = 0; i < trackIDs.size(); i++)
            {
                QString trackLocation;
                int id = trackIDs[i];
                //qDebug() << "track ID:" << id;

                // Try to resolve the (XML's) track ID to a track location.
                if (playlistHashTable.contains(id)) {
                    trackLocation = playlistHashTable[id];
                    //qDebug() << "Resolved to:" << trackLocation;
                }

                // Get the database's track ID (NOT the XML's track ID!)
                int dbTrackId = m_trackDao.getTrackId(trackLocation);

                if (dbTrackId >= 0) {
                    // Add it to the database's playlist.
                    // TODO(XXX): Care if the append succeeded.
                    m_playlistDao.appendTrackToPlaylist(dbTrackId, playlistId);
                }
            }
        }

        QString upgrade_filename = settingPath17.append("DBUPGRADED");
        // now create stub so that the library is not readded next time program loads
        QFile upgradefile(upgrade_filename);
        if (!upgradefile.open(QIODevice::WriteOnly | QIODevice::Text))
            qDebug() << "Couldn't open" << upgrade_filename << "for writing";
        else
        {
            file.write("",0);
            file.close();
        }
    } else {
        qDebug() << errorMsg << " line: " << errorLine << " column: " << errorColumn;
    }

    file.close();
}
Ejemplo n.º 18
0
void ViewTableListWidget::sortByFrequencyCustom(bool ascend)
{
    QList<SortItem> list;
    for(int i = 0; i < rowCount(); i++)
    {
        SortItem newitem;
        newitem.row = i;
        newitem.frequecy = item(i,2)->text().toInt();
        int j = 0;
        if(ascend)
            for(j = list.count() - 1; j >=0 ; j--)
            {
                if(newitem.frequecy >= list.at(j).frequecy) break;
            }
        else
            for(j = list.count() - 1; j >=0 ; j--)
            {
                if(newitem.frequecy <= list.at(j).frequecy) break;
            }
        list.insert(j + 1,newitem);
    }
    QTableWidgetItem * tempitem;
    int temprowcount = rowCount();
    for(int i = 0; i < temprowcount; i++)
    {
        this->insertRow(temprowcount + i);
        tempitem = new QTableWidgetItem(item(list.at(i).row,0)->text());
        tempitem->setIcon(item(list.at(i).row,0)->icon());
        tempitem->setToolTip(item(list.at(i).row,0)->toolTip());
        setItem(temprowcount + i,0,tempitem);
        tempitem = new QTableWidgetItem(item(list.at(i).row,1)->text());
        setItem(temprowcount + i,1,tempitem);
        tempitem = new QTableWidgetItem(item(list.at(i).row,2)->text());
        tempitem->setTextAlignment(Qt::AlignCenter);
        setItem(temprowcount + i,2,tempitem);
        tempitem = new QTableWidgetItem(item(list.at(i).row,3)->text());
        tempitem->setTextAlignment(Qt::AlignCenter);
        setItem(temprowcount + i,3,tempitem);
    }
    for(int i = 0; i < temprowcount; i++)
        removeRow(0);
    list.clear();
}
Ejemplo n.º 19
0
void ShadowrunTool::on_diceroll_clicked()
{

    QList<int> rolledValues;

    int diceCount = this->ui->dicecount->value();

    for(int i = 0; i < diceCount; i++)
    {
        rolledValues.append(randValue());
    }

    //1:  2:  3:  4:  5:  6:
    int counter[6] = {0};

    for(int i = 0; i < rolledValues.size(); i++) {
        if(rolledValues[i] == 1) {
            counter[0]++;
        }
        else if(rolledValues[i] == 2)
        {
            counter[1]++;
        }
        else if(rolledValues[i] == 3)
        {
            counter[2]++;
        }
        else if(rolledValues[i] == 4)
        {
            counter[3]++;
        }
        else if(rolledValues[i] == 5)
        {
            counter[4]++;
        }
        else if(rolledValues[i] == 6)
        {
            counter[5]++;
        }
    }
    QString output(" 1: "+QString::number(counter[0])
            +"\n 2: "+QString::number(counter[1])
            +"\n 3: "+QString::number(counter[2])
            +"\n 4: "+QString::number(counter[3])
            +"\n 5: "+QString::number(counter[4])
            +"\n 6: "+QString::number(counter[5]));
    this->ui->rolledDice->setText(output);

    // set statistics
    if(counter[0] > rolledValues.size()/2)
    {
        this->ui->diceresults->setText("Würfel Egebnisse: \n Patzer");

        if(counter[4] == 0 && counter[5] == 0 && counter[0])
        {
            this->ui->diceresults->setText("Würfel Egebnisse: \n Kritischer Patzer");
        }

    }
    else
    {
        this->ui->diceresults->setText(QString("Würfel Egebnisse: \n 5: ").append(QString::number(counter[4]).append(", 6: ").append(QString::number(counter[5]))).append(" Erfolge: ").append(QString::number(counter[4]+counter[5])));
    }


}
Ejemplo n.º 20
0
void LDFEditor::AddWarningsOfNewFile(double dVers)
{
    QList<QVariant> ouRow;
    int nRow = 0;
    m_pWarningTable->setRowCount(3);


    ouRow.push_back("Warning");
    ouRow.push_back("Valid LDF File should Contain Atleast one signal");
    ouRow.push_back("");
    m_pWarningTable->InsertRow(nRow, ouRow);
    nRow++;

    ouRow.clear();
    ouRow.push_back("Warning");
    ouRow.push_back("Valid LDF File should Contain Atleast one Unconditional Frame");
    ouRow.push_back("");
    m_pWarningTable->InsertRow(nRow, ouRow);
    nRow++;

    ouRow.clear();
    ouRow.push_back("Warning");
    ouRow.push_back("Valid LDF File should Contain Atleast one Schedule Table");
    ouRow.push_back("");
    m_pWarningTable->InsertRow(nRow, ouRow);

    ui.dockPaneWarning->show();
    nRow++;
}
Ejemplo n.º 21
0
void CTimelineWidget::UpdateTimeline()
{
    QLayoutItem *child;
    if(layout() != Q_NULLPTR)
    {
        while (((child = layout()->takeAt(0)) != 0)) {
            //                                    delete child->widget();
            delete child;
        }
        delete layout();
    }   
    m_pLoader->start();
    QHBoxLayout* pHBLayout = new QHBoxLayout(this);
    pHBLayout->setSpacing(6);
    pHBLayout->setContentsMargins(3, 3, 3, 3);
    QPalette Pal(palette());
    Pal.setColor(QPalette::Background, QColor(240,240,240));
    setAutoFillBackground(true);
    setPalette(Pal);

    int iLayout1 = 0;
    int iLayout2 = 0;
    QList<int> lPendingGames = QList<int>();
    for (int i = 0; i < m_pThumbnailList->length(); i++)
    {
        if (m_pThumbnailList->at(i)->GetSyncedID() != QString("")) {
            int j = FindThumbnailIndex(m_pThumbnailList->at(i)->GetSyncedID());
            if (j >= 0) {
                if (i < j)
                {
                    pHBLayout->addWidget(NewColumn(true));
                    AddThumbnail(m_pThumbnailList->at(i), pHBLayout->itemAt(pHBLayout->count()-1)->widget());
                    AddThumbnail(m_pThumbnailList->at(j), pHBLayout->itemAt(pHBLayout->count()-1)->widget());
                    if (m_pThumbnailList->at(i)->GetPlayerID() == CMainWindow::PLAYER_1)
                    {
                        iLayout1 = pHBLayout->count();
                        lPendingGames.append(iLayout1);
                    }
                    else if (m_pThumbnailList->at(i)->GetPlayerID() == CMainWindow::PLAYER_2)
                    {
                        iLayout2 = pHBLayout->count();
                        lPendingGames.append(iLayout2);
                    }
                }
                else
                {
                    if (m_pThumbnailList->at(i)->GetPlayerID() == CMainWindow::PLAYER_1)
                    {
                        iLayout1 = lPendingGames.takeFirst();
                    }
                    else if (m_pThumbnailList->at(i)->GetPlayerID() == CMainWindow::PLAYER_2)
                    {
                        iLayout2 = lPendingGames.takeFirst();
                    }
                }
            }
        }
        else if (m_pThumbnailList->at(i)->GetPlayerID() == CMainWindow::PLAYER_1)
        {
            if (iLayout1 >= pHBLayout->count())
            {
                pHBLayout->addWidget(NewColumn(false));

            }
            if (!AddThumbnail(m_pThumbnailList->at(i), pHBLayout->itemAt(iLayout1)->widget()))
            {
                pHBLayout->insertWidget(iLayout1, NewColumn(false));
                AddThumbnail(m_pThumbnailList->at(i), pHBLayout->itemAt(iLayout1)->widget());
                iLayout2++;
                for (QList<int>::Iterator g = lPendingGames.begin(); g != lPendingGames.end(); g++) {
                    (*g)++;
                }
            }
            iLayout1++;
        }
        else if (m_pThumbnailList->at(i)->GetPlayerID() == CMainWindow::PLAYER_2)
        {
            if (iLayout2 >= pHBLayout->count())
            {
                pHBLayout->addWidget(NewColumn(false));
            }
            if (!AddThumbnail(m_pThumbnailList->at(i), pHBLayout->itemAt(iLayout2)->widget()))
            {
                pHBLayout->insertWidget(iLayout2, NewColumn(false));
                AddThumbnail(m_pThumbnailList->at(i), pHBLayout->itemAt(iLayout2)->widget());
                iLayout1++;
                for (QList<int>::Iterator g = lPendingGames.begin(); g != lPendingGames.end(); g++) {
                    (*g)++;
                }
            }
            iLayout2++;
        }
        else if (m_pThumbnailList->at(i)->GetPlayerID() == CMainWindow::BOTH_PLAYER)
        {
            pHBLayout->addWidget(NewColumn(false));
            AddThumbnail(m_pThumbnailList->at(i), pHBLayout->itemAt(pHBLayout->count()-1)->widget());
            iLayout1 = pHBLayout->count();
            iLayout2 = pHBLayout->count();
        }
    }

    setLayout(pHBLayout);
}
//-----------------------------------------------------------------------------
void ctkTransferFunctionRepresentation::computeCurve()
{
  Q_D(ctkTransferFunctionRepresentation);

  int count = d->TransferFunction ? d->TransferFunction->count() : 0;
  if (count <= 0)
    {
    return;
    }

  d->TransferFunction->range(d->WorldRangeX[0], d->WorldRangeX[1]);
  d->WorldRangeY[0] = this->posY(d->TransferFunction->minValue());
  d->WorldRangeY[1] = this->posY(d->TransferFunction->maxValue());

  d->RangeXDiff   = this->computeRangeXDiff(d->rect(), d->WorldRangeX);
  d->RangeXOffSet = this->computeRangeXOffset(d->WorldRangeX);

  d->RangeYDiff   = this->computeRangeYDiff(d->rect(), d->WorldRangeY);
  d->RangeYOffSet = this->computeRangeYOffset(d->WorldRangeY);

  ctkControlPoint* startCP = d->TransferFunction->controlPoint(0);
  ctkControlPoint* nextCP = 0;

  QPointF startPos = this->mapPointToScene(startCP);

  d->Points.clear();
  d->Points << startPos;

  d->Path = QPainterPath();
  d->Path.moveTo(startPos);
  for(int i = 1; i < count; ++i)
    {
    nextCP = d->TransferFunction->controlPoint(i);
    if (this->transferFunction()->isDiscrete())
      {
      QPointF nextPos = this->mapPointToScene(nextCP);
      qreal midPosX = (startPos.x() + nextPos.x()) / 2.;

      d->Path.lineTo(QPointF(midPosX, startPos.y()));
      d->Path.lineTo(QPointF(midPosX, nextPos.y()));

      d->Points << nextPos;
      startPos = nextPos;
      if (i == count -1)
        {
        d->Path.lineTo(nextPos);
        }
      }
    else if (dynamic_cast<ctkNonLinearControlPoint*>(startCP))
      {
      QList<ctkPoint> points = this->nonLinearPoints(startCP, nextCP);
      int j;
      for (j = 1; j < points.count(); ++j)
        {
        d->Path.lineTo(this->mapPointToScene(points[j]));
        }
      j = points.count() - 1;
      d->Points << this->mapPointToScene(points[j]);
      }
    else //dynamic_cast<ctkBezierControlPoint*>(startCP))
      {
      QList<ctkPoint> points = this->bezierParams(startCP, nextCP);
      QList<ctkPoint>::iterator it = points.begin();
      QList<QPointF> bezierPoints;
      foreach(const ctkPoint& p, points)
        {
        bezierPoints << this->mapPointToScene(p);
        }
      d->Path.cubicTo(bezierPoints[1], bezierPoints[2], bezierPoints[3]);
      d->Points << bezierPoints[3];
      }
    //qDebug() << i << points[0] << points[1] << points[2] << points[3];
    delete startCP;
    startCP = nextCP;
    }
Ejemplo n.º 23
0
KrPopupMenu::KrPopupMenu(KrPanel *thePanel, QWidget *parent) : QMenu(parent), panel(thePanel), empty(false),
        multipleSelections(false), actions(0), _item(0)
{
#ifdef __LIBKONQ__
    konqMenu = 0;
    konqMenuActions = 0;
#endif

    KrViewItemList items;
    panel->view->getSelectedKrViewItems(&items);

    for (KrViewItemList::Iterator it = items.begin(); it != items.end(); ++it) {
        vfile *file = panel->func->files()->vfs_search(((*it)->name()));
        QUrl url = file->vfile_getUrl();
        _items.append(KFileItem(url, file->vfile_getMime(), file->vfile_getMode()));
    }

    if (items.empty()) {
        addCreateNewMenu();
        addSeparator();
        addEmptyMenuEntries();
        return;
    } else if (items.size() > 1) multipleSelections = true;

    QList<QString> protocols;
    for (int i = 0; i < items.size(); ++i) {
        protocols.append(panel->func->getVFile(items[ i ]) ->vfile_getUrl().scheme());
    }
    bool inTrash = protocols.contains("trash");
    bool trashOnly = (protocols.count() == 1) && (protocols[ 0 ] == "trash");

    KrViewItem *item = items.first();
    vfile *vf = panel->func->getVFile(item);
    _item = &_items.first();

    // ------------ the OPEN/BROWSE option - open preferred service
    QAction * openAct = addAction(i18n("Open/Run"));
    openAct->setData(QVariant(OPEN_ID));
    if (!multipleSelections) {   // meaningful only if one file is selected
        openAct->setIcon(item->icon());
        openAct->setText(vf->vfile_isExecutable() && !vf->vfile_isDir() ? i18n("Run") : i18n("Open"));
        // open in a new tab (if folder)
        if (vf->vfile_isDir()) {
            QAction * openTab = addAction(i18n("Open in New Tab"));
            openTab->setData(QVariant(OPEN_TAB_ID));
            openTab->setIcon(krLoader->loadIcon("tab-new", KIconLoader::Panel));
            openTab->setText(i18n("Open in New Tab"));
        }
        QUrl arcPath = panel->func->browsableArchivePath(vf->vfile_getName());
        if (!arcPath.isEmpty()) {
            bool theArchiveMustBeBrowsedAsADirectory = KConfigGroup(krConfig, "Archives").readEntry("ArchivesAsDirectories", _ArchivesAsDirectories) &&
                                                       KRarcHandler::arcSupported(vf->vfile_getMime());
            if (!theArchiveMustBeBrowsedAsADirectory) {
                // Add an option to browse the archive
                QAction *browseAct = addAction(i18n("Browse"));
                browseAct->setData(QVariant(BROWSE_ID));
                browseAct->setIcon(krLoader->loadIcon("", KIconLoader::Panel));
                browseAct->setText(i18n("Browse Archive"));
            }
        }
        addSeparator();
    }

    // ------------- Preview - normal vfs only ?
    if (panel->func->files()->vfs_getType() == vfs::VFS_NORMAL) {
        // create the preview popup
        QStringList names;
        panel->gui->getSelectedNames(&names);
        preview.setUrls(panel->func->files() ->vfs_getFiles(names));
        QAction *pAct = addMenu(&preview);
        pAct->setData(QVariant(PREVIEW_ID));
        pAct->setText(i18n("Preview"));
    }

    // -------------- Open with: try to find-out which apps can open the file
    // this too, is meaningful only if one file is selected or if all the files
    // have the same mimetype !
    QString mime = panel->func->getVFile(item)->vfile_getMime();
    // check if all the list have the same mimetype
    for (int i = 1; i < items.size(); ++i) {
        if (panel->func->getVFile(items[ i ]) ->vfile_getMime() != mime) {
            mime.clear();
            break;
        }
    }
    if (!mime.isEmpty()) {
        offers = KMimeTypeTrader::self()->query(mime);
        for (int i = 0; i < offers.count(); ++i) {
            QExplicitlySharedDataPointer<KService> service = offers[i];
            if (service->isValid() && service->isApplication()) {
                openWith.addAction(krLoader->loadIcon(service->icon(), KIconLoader::Small), service->name())->setData(QVariant(SERVICE_LIST_ID + i));
            }
        }
        openWith.addSeparator();
        if (vf->vfile_isDir())
            openWith.addAction(krLoader->loadIcon("utilities-terminal", KIconLoader::Small), i18n("Terminal"))->setData(QVariant(OPEN_TERM_ID));
        openWith.addAction(i18n("Other..."))->setData(QVariant(CHOOSE_ID));
        QAction *owAct = addMenu(&openWith);
        owAct->setData(QVariant(OPEN_WITH_ID));
        owAct->setText(i18n("Open With"));
        addSeparator();
    }

    // --------------- user actions
    QAction *uAct = new UserActionPopupMenu(panel->func->files()->vfs_getFile(item->name()));
    addAction(uAct);
    uAct->setText(i18n("User Actions"));

#ifdef __LIBKONQ__
    // -------------- konqueror menu
    // This section adds all Konqueror/Dolphin menu items.
    // It's now updated to KDE4 and working, I've just commented it out.
    // Section below this one adds only servicemenus.

    // Append only servicemenus

    //TODO: deprecated since KDE4.3: remove these three lines
    KonqPopupMenuInformation info;
    info.setItems(_items);
    info.setParentWidget(this);

    konqMenuActions = new KonqMenuActions();
    //TODO: deprecated since KDE4.3: remove this line, use two commented lines
    konqMenuActions->setPopupMenuInfo(info);
    //konqMenuActions->setParentWidget( this );
    //konqMenuActions->setItemListProperties( _items );
    konqMenuActions->addActionsTo(this);

    addSeparator();
#endif

    // ------------- 'create new' submenu
    addCreateNewMenu();
    addSeparator();

    // ---------- COPY
    addAction(i18n("Copy..."))->setData(QVariant(COPY_ID));
    if (panel->func->files() ->vfs_isWritable()) {
        // ------- MOVE
        addAction(i18n("Move..."))->setData(QVariant(MOVE_ID));
        // ------- RENAME - only one file
        if (!multipleSelections && !inTrash)
            addAction(i18n("Rename"))->setData(QVariant(RENAME_ID));

        // -------- MOVE TO TRASH
        KConfigGroup saver(krConfig, "General");
        bool trash = saver.readEntry("Move To Trash", _MoveToTrash);
        if (trash && !inTrash)
            addAction(i18n("Move to Trash"))->setData(QVariant(TRASH_ID));
        // -------- DELETE
        addAction(i18n("Delete"))->setData(QVariant(DELETE_ID));
        // -------- SHRED - only one file
        /*      if ( panel->func->files() ->vfs_getType() == vfs::VFS_NORMAL &&
                    !vf->vfile_isDir() && !multipleSelections )
                 addAction( i18n( "Shred" ) )->setData( QVariant( SHRED_ID ) );*/
    }

    // ---------- link handling
    // create new shortcut or redirect links - only on local directories:
    if (panel->func->files() ->vfs_getType() == vfs::VFS_NORMAL) {
        addSeparator();
        linkPopup.addAction(i18n("New Symlink..."))->setData(QVariant(NEW_SYMLINK_ID));
        linkPopup.addAction(i18n("New Hardlink..."))->setData(QVariant(NEW_LINK_ID));
        if (panel->func->getVFile(item)->vfile_isSymLink())
            linkPopup.addAction(i18n("Redirect Link..."))->setData(QVariant(REDIRECT_LINK_ID));
        QAction *linkAct = addMenu(&linkPopup);
        linkAct->setData(QVariant(LINK_HANDLING_ID));
        linkAct->setText(i18n("Link Handling"));
    }
    addSeparator();

    // ---------- calculate space
    if (panel->func->files() ->vfs_getType() == vfs::VFS_NORMAL && (vf->vfile_isDir() || multipleSelections))
        addAction(panel->gui->actions()->actCalculate);

    // ---------- mount/umount/eject
    if (panel->func->files() ->vfs_getType() == vfs::VFS_NORMAL && vf->vfile_isDir() && !multipleSelections) {
        if (krMtMan.getStatus(panel->func->files() ->vfs_getFile(item->name()).path()) == KMountMan::MOUNTED)
            addAction(i18n("Unmount"))->setData(QVariant(UNMOUNT_ID));
        else if (krMtMan.getStatus(panel->func->files() ->vfs_getFile(item->name()).path()) == KMountMan::NOT_MOUNTED)
            addAction(i18n("Mount"))->setData(QVariant(MOUNT_ID));
        if (krMtMan.ejectable(panel->func->files() ->vfs_getFile(item->name()).path()))
            addAction(i18n("Eject"))->setData(QVariant(EJECT_ID));
    }

    // --------- send by mail
    if (KrServices::supportedTools().contains("MAIL") && !vf->vfile_isDir()) {
        addAction(i18n("Send by Email"))->setData(QVariant(SEND_BY_EMAIL_ID));
    }

    // --------- empty trash
    if (trashOnly) {
        addAction(i18n("Restore"))->setData(QVariant(RESTORE_TRASHED_FILE_ID));
        addAction(i18n("Empty Trash"))->setData(QVariant(EMPTY_TRASH_ID));
    }

#ifdef SYNCHRONIZER_ENABLED
    // --------- synchronize
    if (panel->view->numSelected()) {
        addAction(i18n("Synchronize Selected Files..."))->setData(QVariant(SYNC_SELECTED_ID));
    }
#endif

    // --------- copy/paste
    addSeparator();
    addAction(i18n("Copy to Clipboard"))->setData(QVariant(COPY_CLIP_ID));
    if (panel->func->files() ->vfs_isWritable()) {
        addAction(i18n("Cut to Clipboard"))->setData(QVariant(MOVE_CLIP_ID));
        addAction(i18n("Paste from Clipboard"))->setData(QVariant(PASTE_CLIP_ID));
    }
    addSeparator();

    // --------- properties
    addAction(panel->gui->actions()->actProperties);
}
Ejemplo n.º 24
0
QList <Proceso *> ListaProcesos::getListaProcesosOrto(DataZoneProject *dataZoPro)
{
    QList <Proceso *> listaProcesos;
    if(dataZoPro->getCoordinateSystem()==DataZoneProject::Ed50)
    {
        if(dataZoPro->getFootPrintMask()==false && dataZoPro->getCutDtm()==false)
        {
                listaProcesos.append(new ProcesoSubScene(this,_qMapEjecutables.value("exeSubScene")));
        }
        if(dataZoPro->getFootPrintMask() && dataZoPro->getCutDtm())
        {
            listaProcesos.append(new ProcesoSubScene(this,_qMapEjecutables.value("exeSubScene")));
            listaProcesos.append(new ProcesoFootPrintMask(this,_qMapEjecutables.value("exeFootPrintMask")));
            listaProcesos.append(new ProcesoGeoTrans(this,_qMapEjecutables.value("exeGeoTransform")));
            listaProcesos.append(new ProcesoResize(this,_qMapEjecutables.value("exeResize")));
            listaProcesos.append(new ProcesoCutFiles(this,_qMapEjecutables.value("exeSubScene")));
        }
        if(dataZoPro->getFootPrintMask()==false && dataZoPro->getCutDtm())
        {
            listaProcesos.append(new ProcesoSubScene(this,_qMapEjecutables.value("exeSubScene")));
            listaProcesos.append(new ProcesoGeoTrans(this,_qMapEjecutables.value("exeGeoTransform")));
            listaProcesos.append(new ProcesoResize(this,_qMapEjecutables.value("exeResize")));
            listaProcesos.append(new ProcesoCutFiles(this,_qMapEjecutables.value("exeSubScene")));
        }
        if(dataZoPro->getFootPrintMask() && dataZoPro->getCutDtm()==false)
        {
            listaProcesos.append(new ProcesoSubScene(this,_qMapEjecutables.value("exeSubScene")));
            listaProcesos.append(new ProcesoFootPrintMask(this,_qMapEjecutables.value("exeFootPrintMask")));
            listaProcesos.append(new ProcesoGeoTrans(this,_qMapEjecutables.value("exeGeoTransform")));
            listaProcesos.append(new ProcesoResize(this,_qMapEjecutables.value("exeResize")));
        }
    }

    else //si el sistema de coordenadas es Etrs89 y Ntf
    {
        if(dataZoPro->getFootPrintMask()==false && dataZoPro->getCutDtm()==false)
        {
                listaProcesos.append(new ProcesoSubScene(this,_qMapEjecutables.value("exeSubScene")));
        }
        if(dataZoPro->getFootPrintMask() && dataZoPro->getCutDtm())
        {
            listaProcesos.append(new ProcesoSubScene(this,_qMapEjecutables.value("exeSubScene")));
            listaProcesos.append(new ProcesoResize(this,_qMapEjecutables.value("exeResize")));
            listaProcesos.append(new ProcesoFootPrintMask(this,_qMapEjecutables.value("exeFootPrintMask")));
            listaProcesos.append(new ProcesoCutFiles(this,_qMapEjecutables.value("exeSubScene")));
        }
        if(dataZoPro->getFootPrintMask()==false && dataZoPro->getCutDtm())
        {
            listaProcesos.append(new ProcesoSubScene(this,_qMapEjecutables.value("exeSubScene")));
            listaProcesos.append(new ProcesoResize(this,_qMapEjecutables.value("exeResize")));
            listaProcesos.append(new ProcesoCutFiles(this,_qMapEjecutables.value("exeSubScene")));
        }
        if(dataZoPro->getFootPrintMask() && dataZoPro->getCutDtm()==false)
        {
            listaProcesos.append(new ProcesoSubScene(this,_qMapEjecutables.value("exeSubScene")));
            listaProcesos.append(new ProcesoFootPrintMask(this,_qMapEjecutables.value("exeFootPrintMask")));
        }
    }
    return listaProcesos;
}
Ejemplo n.º 25
0
void QgsGeometryGapCheck::collectErrors( const QMap<QString, QgsFeaturePool *> &featurePools, QList<QgsGeometryCheckError *> &errors, QStringList &messages, QgsFeedback *feedback, const LayerFeatureIds &ids ) const
{
  if ( feedback )
    feedback->setProgress( feedback->progress() + 1.0 );

  QVector<QgsGeometry> geomList;


  QMap<QString, QgsFeatureIds> featureIds = ids.isEmpty() ? allLayerFeatureIds( featurePools ) : ids.toMap();
  const QgsGeometryCheckerUtils::LayerFeatures layerFeatures( featurePools, featureIds, compatibleGeometryTypes(), nullptr, mContext, true );
  for ( const QgsGeometryCheckerUtils::LayerFeature &layerFeature : layerFeatures )
  {
    geomList.append( layerFeature.geometry() );

    if ( feedback && feedback->isCanceled() )
    {
      geomList.clear();
      break;
    }
  }

  if ( geomList.isEmpty() )
  {
    return;
  }

  std::unique_ptr< QgsGeometryEngine > geomEngine = QgsGeometryCheckerUtils::createGeomEngine( nullptr, mContext->tolerance );
  geomEngine->prepareGeometry();

  // Create union of geometry
  QString errMsg;
  std::unique_ptr<QgsAbstractGeometry> unionGeom( geomEngine->combine( geomList, &errMsg ) );
  if ( !unionGeom )
  {
    messages.append( tr( "Gap check: %1" ).arg( errMsg ) );
    return;
  }

  // Get envelope of union
  geomEngine = QgsGeometryCheckerUtils::createGeomEngine( unionGeom.get(), mContext->tolerance );
  geomEngine->prepareGeometry();
  std::unique_ptr<QgsAbstractGeometry> envelope( geomEngine->envelope( &errMsg ) );
  if ( !envelope )
  {
    messages.append( tr( "Gap check: %1" ).arg( errMsg ) );
    return;
  }

  // Buffer envelope
  geomEngine = QgsGeometryCheckerUtils::createGeomEngine( envelope.get(), mContext->tolerance );
  geomEngine->prepareGeometry();
  QgsAbstractGeometry *bufEnvelope = geomEngine->buffer( 2, 0, GEOSBUF_CAP_SQUARE, GEOSBUF_JOIN_MITRE, 4. );  //#spellok  //#spellok
  envelope.reset( bufEnvelope );

  // Compute difference between envelope and union to obtain gap polygons
  geomEngine = QgsGeometryCheckerUtils::createGeomEngine( envelope.get(), mContext->tolerance );
  geomEngine->prepareGeometry();
  std::unique_ptr<QgsAbstractGeometry> diffGeom( geomEngine->difference( unionGeom.get(), &errMsg ) );
  if ( !diffGeom )
  {
    messages.append( tr( "Gap check: %1" ).arg( errMsg ) );
    return;
  }

  // For each gap polygon which does not lie on the boundary, get neighboring polygons and add error
  for ( int iPart = 0, nParts = diffGeom->partCount(); iPart < nParts; ++iPart )
  {
    std::unique_ptr<QgsAbstractGeometry> gapGeom( QgsGeometryCheckerUtils::getGeomPart( diffGeom.get(), iPart )->clone() );
    // Skip the gap between features and boundingbox
    const double spacing = context()->tolerance;
    if ( gapGeom->boundingBox().snappedToGrid( spacing ) == envelope->boundingBox().snappedToGrid( spacing ) )
    {
      continue;
    }

    // Skip gaps above threshold
    if ( ( mGapThresholdMapUnits > 0 && gapGeom->area() > mGapThresholdMapUnits ) || gapGeom->area() < mContext->reducedTolerance )
    {
      continue;
    }

    QgsRectangle gapAreaBBox = gapGeom->boundingBox();

    // Get neighboring polygons
    QMap<QString, QgsFeatureIds> neighboringIds;
    const QgsGeometryCheckerUtils::LayerFeatures layerFeatures( featurePools, featureIds.keys(), gapAreaBBox, compatibleGeometryTypes(), mContext );
    for ( const QgsGeometryCheckerUtils::LayerFeature &layerFeature : layerFeatures )
    {
      const QgsGeometry geom = layerFeature.geometry();
      if ( QgsGeometryCheckerUtils::sharedEdgeLength( gapGeom.get(), geom.constGet(), mContext->reducedTolerance ) > 0 )
      {
        neighboringIds[layerFeature.layer()->id()].insert( layerFeature.feature().id() );
        gapAreaBBox.combineExtentWith( layerFeature.geometry().boundingBox() );
      }
    }

    if ( neighboringIds.isEmpty() )
    {
      continue;
    }

    // Add error
    double area = gapGeom->area();
    errors.append( new QgsGeometryGapCheckError( this, QString(), QgsGeometry( gapGeom.release() ), neighboringIds, area, gapAreaBBox ) );
  }
}
Ejemplo n.º 26
0
QByteArray Token::signRequest(const QUrl& requestUrl, Token::AuthMethod authMethod, Token::HttpMethod method, const QMultiMap<QString, QString>& parameters) const
{
	QString timestamp;
	QString nonce;

	if (d->consumerKey == "test_token") { // Set known values for unit-testing
		timestamp = "1234567890";	//Feb 13, 2009, 23:31:30 GMT
		nonce = "ABCDEF";
	} else {
#if QT_VERSION >= 0x040700
		timestamp = QString::number(QDateTime::currentDateTimeUtc().toTime_t());
#else
		timestamp = QString::number(QDateTime::currentDateTime().toUTC().toTime_t());
#endif
		nonce = QString::number(qrand());
	}

	if (!requestUrl.isValid()) {
		qWarning() << "OAuth::Token: Invalid url. The request will probably be invalid";
	}

	// Step 1. Get all the oauth params for this request

	QMultiMap<QString, QString> oauthParams;

	oauthParams.insert("oauth_consumer_key", d->consumerKey);
    if(d->serviceType == "dbox")
        oauthParams.insert("oauth_signature_method", "PLAINTEXT");
    else
        oauthParams.insert("oauth_signature_method", "HMAC-SHA1");
	oauthParams.insert("oauth_timestamp", timestamp);
	oauthParams.insert("oauth_nonce", nonce);
	oauthParams.insert("oauth_version", "1.0");

	switch (d->tokenType) {
	case Token::InvalidToken:
		oauthParams.insert("oauth_callback", d->callbackUrl.toString());
		break;

	case Token::RequestToken:
		oauthParams.insert("oauth_token", d->oauthToken);
		oauthParams.insert("oauth_verifier", d->oauthVerifier);
		break;

	case Token::AccessToken:
		oauthParams.insert("oauth_token", d->oauthToken);
		break;
	}

	// Step 2. Take the parameters from the url, and add the oauth params to them

	QMultiMap<QString, QString> allParams = oauthParams;
	QList<QPair<QString, QString> > queryItems = requestUrl.queryItems();
	for(int i = 0; i < queryItems.count(); ++i) {
		allParams.insert(queryItems[i].first, queryItems[i].second);
	}

	allParams.unite(parameters);

	// Step 3. Calculate the signature from those params, and append the signature to the oauth params

	QString signature = generateSignature(requestUrl, allParams, method);
	oauthParams.insert("oauth_signature", signature);

	// Step 4. Concatenate all oauth params into one comma-separated string

	QByteArray authHeader;

	if (authMethod == Sasl) {
		authHeader = "GET ";
		authHeader.append(requestUrl.toString() + " ");
	} else {
		authHeader = "OAuth ";
	}

	QMultiMap<QString, QString>::const_iterator p = oauthParams.constBegin();
	while (p != oauthParams.constEnd()) {
		authHeader += QString("%1=\"%2\",").arg(p.key()).arg(encode(p.value()));
		++p;
	}
	authHeader.chop(1); // remove the last character (the trailing ",")

	return authHeader;
}
Ejemplo n.º 27
0
void
RemapHistogramLine::mousePress(int xpos, int button)
{
  m_startDrag = -1;
  m_activeTick = -1;
  m_activeTickNumber = -1;

  {
    int tk;
    float frc;
    
    frc = (xpos-m_start)/(float)m_width;
    tk = m_tickMinKey + frc*(m_tickMaxKey-m_tickMinKey);
    
    int nearest = -1;
    int nd = 100000000;
    QList<uint> keys = m_ticks.keys();
    for(uint i=0; i<m_ticks.size(); i++)
      {
	int v = keys[i];
	int d = qAbs(tk-v);
	if (d < nd)
	  {
	    nd = d;
	    nearest = i;
	  }
      }
    int delta = (10.0f/(float)m_width)*(m_tickMaxKey-m_tickMinKey);
    if (nd<delta)
      m_activeTick = keys[nearest];
  }

//  frc = ((xpos-15)-m_start)/(float)m_width;
//  tk1 = m_tickMinKey + frc*(m_tickMaxKey-m_tickMinKey);
//
//  frc = ((xpos+15)-m_start)/(float)m_width;
//  tk2 = m_tickMinKey + frc*(m_tickMaxKey-m_tickMinKey);
//
//  QList<uint> keys = m_ticks.keys();
//  for(uint i=0; i<m_ticks.size(); i++)
//    {
//      int v = keys[i];
//      if (v >= tk1 && v <= tk2)
//	{
//	  m_activeTick = keys[i];
//	  break;
//	}
//    }

//  bool deletedTick = false;
//  bool addedTick = false;
//  int tickNumber = -1;
//  if (button == Qt::RightButton)
//    {
//      if (m_activeTick != -1)
//	{ // we need to delete this tick
//	  int tkn = -1;
//	  QList<uint> keys = m_ticks.keys();
//	  for(int k=0; k<keys.size(); k++)
//	    if (keys[k] == m_activeTick)
//	      {
//		tkn = k;
//		break;
//	      }
//	  if (tkn == 0 || tkn == m_ticks.size()-1)
//	    {
//	      QMessageBox::information(0, "Error",
//				       "End markers cannot be removed");
//	      return;
//	    }
//	  m_ticks.remove(m_activeTick);
//	  m_ticksOriginal.remove(m_ticksOriginal.keys()[tkn]);
//	  m_activeTick = -1;
//
//	  deletedTick = true;
//	  tickNumber = tkn;
//	}
//    }
//  else if (m_activeTick == -1)
//    { // we need to add one tick here
//      QList<uint> keys = m_ticks.keys();
//
//      frc = (xpos-m_start)/(float)m_width;
//      uint tk = m_tickMinKey + frc*(m_tickMaxKey-m_tickMinKey);
//      int tkn = -1;
//
//      if (m_ticksOriginal.contains(tk))
//	{
//	  QMessageBox::information(0, "Error",
//				   "A marker already exists at this place");
//	  return;
//	}
//
//
//      if (tk <= keys[0] ||
//	  tk >= keys[keys.size()-1])
//	{
//	  QMessageBox::information(0, "Error",
//				   "Cannot add point beyond the ends");
//	  return;
//	}
//
//      // add the tick
//      m_ticks[tk] = tk;
//      m_ticksOriginal[tk] = tk;
//      m_activeTick = tk;
//      
//
//      // now get the previous tick and relative proportions
//      for(int k=0; k<keys.size(); k++)
//	{
//	  if (keys[k] < tk)
//	    tkn = k;
//	  else
//	    break;
//	}
//      frc = ( ((float)tk-(float)keys[tkn]) /
//	      ((float)keys[tkn+1]-(float)keys[tkn]) );
//      addedTick = true;
//      tickNumber = tkn+1;
//    }

  m_activeB1 = m_tickMinKey;
  m_activeB2 = m_tickMaxKey;
  if (m_activeTick > -1)
    {
      QList<uint> keys = m_ticks.keys();

      for(int k=0; k<keys.size(); k++)
	if (keys[k] == m_activeTick)
	  {
	    m_activeTickNumber = k;
	    break;
	  }


      for(int k=0; k<keys.size(); k++)
	{
	  if (m_activeTick > keys[k])
	    m_activeB1 = keys[k];
	}
      for(int k=keys.size()-1; k>=0; k--)
	{
	  if (m_activeTick < keys[k])
	    m_activeB2 = keys[k];
	}
    }
  
  int delta = 11.0*(m_tickMaxKey-m_tickMinKey)/(float)m_width;
  if (m_activeTickNumber > 0)
    m_activeB1 += delta;
  if (m_activeTickNumber < m_ticks.size()-1)
    m_activeB2 -= delta;

//  if (deletedTick)
//    emit removeTick();
//  else if (addedTick)
//    emit addTick(tickNumber);

  if (m_activeTick < 0)
    {
      QList<uint> tkeys = m_ticks.keys();
      float frc = (xpos-m_start)/(float)m_width;
      uint tk = m_tickMinKey + frc*(m_tickMaxKey-m_tickMinKey);
      if (tk > tkeys[0] && tk < tkeys[1])
	m_startDrag = tk;	  
    }
}
Ejemplo n.º 28
0
/*!
   \brief Render an image from data and color map.

   For each pixel of area the value is mapped into a color.

  \param xMap X-Scale Map
  \param yMap Y-Scale Map
  \param area Requested area for the image in scale coordinates
  \param imageSize Size of the requested image

   \return A QImage::Format_Indexed8 or QImage::Format_ARGB32 depending
           on the color map.

   \sa QwtRasterData::value(), QwtColorMap::rgb(),
       QwtColorMap::colorIndex()
*/
QImage QwtPlotSpectrogram::renderImage(
    const QwtScaleMap &xMap, const QwtScaleMap &yMap,
    const QRectF &area, const QSize &imageSize ) const
{
    if ( imageSize.isEmpty() || d_data->data == NULL 
        || d_data->colorMap == NULL )
    {
        return QImage();
    }

    const QwtInterval intensityRange = d_data->data->interval( Qt::ZAxis );
    if ( !intensityRange.isValid() )
        return QImage();

    QImage::Format format = ( d_data->colorMap->format() == QwtColorMap::RGB )
        ? QImage::Format_ARGB32 : QImage::Format_Indexed8;

    QImage image( imageSize, format );

    if ( d_data->colorMap->format() == QwtColorMap::Indexed )
        image.setColorTable( d_data->colorMap->colorTable( intensityRange ) );

    d_data->data->initRaster( area, image.size() );

#if DEBUG_RENDER
    QElapsedTimer time;
    time.start();
#endif

#if QT_VERSION >= 0x040400 && !defined(QT_NO_QFUTURE)
    uint numThreads = renderThreadCount();

    if ( numThreads <= 0 )
        numThreads = QThread::idealThreadCount();

    if ( numThreads <= 0 )
        numThreads = 1;

    const int numRows = imageSize.height() / numThreads;

    QList< QFuture<void> > futures;
    for ( uint i = 0; i < numThreads; i++ )
    {
        QRect tile( 0, i * numRows, image.width(), numRows );
        if ( i == numThreads - 1 )
        {
            tile.setHeight( image.height() - i * numRows );
            renderTile( xMap, yMap, tile, &image );
        }
        else
        {
            futures += QtConcurrent::run(
                this, &QwtPlotSpectrogram::renderTile,
                xMap, yMap, tile, &image );
        }
    }
    for ( int i = 0; i < futures.size(); i++ )
        futures[i].waitForFinished();

#else // QT_VERSION < 0x040400
    const QRect tile( 0, 0, image.width(), image.height() );
    renderTile( xMap, yMap, tile, &image );
#endif

#if DEBUG_RENDER
    const qint64 elapsed = time.elapsed();
    qDebug() << "renderImage" << imageSize << elapsed;
#endif

    d_data->data->discardRaster();

    return image;
}
Ejemplo n.º 29
0
RenderOptionsDialog::RenderOptionsDialog()
    : QDialog(0, Qt::CustomizeWindowHint | Qt::WindowTitleHint)
{
    setWindowOpacity(0.75);
    setWindowTitle(tr("Options (double click to flip)"));
    QGridLayout *layout = new QGridLayout;
    setLayout(layout);
    layout->setColumnStretch(1, 1);

    int row = 0;

    QCheckBox *check = new QCheckBox(tr("Dynamic cube map"));
    check->setCheckState(Qt::Unchecked);
    // Dynamic cube maps are only enabled when multi-texturing and render to texture are available.
    check->setEnabled(glActiveTexture && glGenFramebuffersEXT);
    connect(check, SIGNAL(stateChanged(int)), this, SIGNAL(dynamicCubemapToggled(int)));
    layout->addWidget(check, 0, 0, 1, 2);
    ++row;

    QPalette palette;

    // Load all .par files
    // .par files have a simple syntax for specifying user adjustable uniform variables.
    QSet<QByteArray> uniforms;
    QList<QString> filter = QStringList("*.par");
    QList<QFileInfo> files = QDir(":/res/boxes/").entryInfoList(filter, QDir::Files | QDir::Readable);

    foreach (QFileInfo fileInfo, files) {
        QFile file(fileInfo.absoluteFilePath());
        if (file.open(QIODevice::ReadOnly)) {
            while (!file.atEnd()) {
                QList<QByteArray> tokens = file.readLine().simplified().split(' ');
                QList<QByteArray>::const_iterator it = tokens.begin();
                if (it == tokens.end())
                    continue;
                QByteArray type = *it;
                if (++it == tokens.end())
                    continue;
                QByteArray name = *it;
                bool singleElement = (tokens.size() == 3); // type, name and one value
                char counter[10] = "000000000";
                int counterPos = 8; // position of last digit
                while (++it != tokens.end()) {
                    m_parameterNames << name;
                    if (!singleElement) {
                        m_parameterNames.back() += "[";
                        m_parameterNames.back() += counter + counterPos;
                        m_parameterNames.back() += "]";
                        int j = 8; // position of last digit
                        ++counter[j];
                        while (j > 0 && counter[j] > '9') {
                            counter[j] = '0';
                            ++counter[--j];
                        }
                        if (j < counterPos)
                            counterPos = j;
                    }

                    if (type == "color") {
                        layout->addWidget(new QLabel(m_parameterNames.back()));
                        bool ok;
                        ColorEdit *colorEdit = new ColorEdit(it->toUInt(&ok, 16), m_parameterNames.size() - 1);
                        m_parameterEdits << colorEdit;
                        layout->addWidget(colorEdit);
                        connect(colorEdit, SIGNAL(colorChanged(QRgb,int)), this, SLOT(setColorParameter(QRgb,int)));
                        ++row;
                    } else if (type == "float") {
                        layout->addWidget(new QLabel(m_parameterNames.back()));
                        bool ok;
                        FloatEdit *floatEdit = new FloatEdit(it->toFloat(&ok), m_parameterNames.size() - 1);
                        m_parameterEdits << floatEdit;
                        layout->addWidget(floatEdit);
                        connect(floatEdit, SIGNAL(valueChanged(float,int)), this, SLOT(setFloatParameter(float,int)));
                        ++row;
                    }
                }
Ejemplo n.º 30
-1
void CanvasObject::dropEvent(QDropEvent *event) {
  if(event->mimeData()->hasUrls()) {
    QList<QUrl> list = event->mimeData()->urls();
    if(list.count() == 1) cartridge.loadNormal(list.at(0).toLocalFile().toUtf8().constData());
  }
}