Esempio n. 1
0
WalletModel::SendCoinsReturn WalletModel::sendCoins(const QList<SendCoinsRecipient> &recipients, int nRefHeight)
{
    mpq total = 0;
    QSet<QString> setAddress;
    QString hex;

    if(recipients.empty())
    {
        return OK;
    }

    if ( nRefHeight < 0 )
        nRefHeight = nBestHeight;

    // Pre-check input data for validity
    foreach(const SendCoinsRecipient &rcp, recipients)
    {
        if(!validateAddress(rcp.address))
        {
            return InvalidAddress;
        }
        setAddress.insert(rcp.address);

        if(rcp.amount <= 0)
        {
            return InvalidAmount;
        }
        total += rcp.amount;
    }

    if(recipients.size() > setAddress.size())
    {
        return DuplicateAddress;
    }

    if(total > getBalance(nRefHeight))
    {
        return AmountExceedsBalance;
    }

    mpq qBalReq = total + nTransactionFee;
    if(qBalReq > getBalance(nRefHeight))
    {
        return SendCoinsReturn(AmountWithFeeExceedsBalance, nTransactionFee);
    }

    {
        LOCK2(cs_main, wallet->cs_wallet);

        // Sendmany
        std::vector<std::pair<CScript, mpq> > vecSend;
        foreach(const SendCoinsRecipient &rcp, recipients)
        {
            CScript scriptPubKey;
            scriptPubKey.SetDestination(CNiCoInAddress(rcp.address.toStdString()).Get());
            vecSend.push_back(make_pair(scriptPubKey, rcp.amount));
        }

        CWalletTx wtx;
        CReserveKey keyChange(wallet);
        mpq nFeeRequired = 0;
        bool fCreated = wallet->CreateTransaction(vecSend, nRefHeight, wtx, keyChange, nFeeRequired);

        if(!fCreated)
        {
            if(qBalReq > wallet->GetBalance(nRefHeight))
            {
                return SendCoinsReturn(AmountWithFeeExceedsBalance, nFeeRequired);
            }
            return TransactionCreationFailed;
        }
        if(!uiInterface.ThreadSafeAskFee(nFeeRequired, tr("Sending...").toStdString()))
        {
            return Aborted;
        }
        if(!wallet->CommitTransaction(wtx, keyChange))
        {
            return TransactionCommitFailed;
        }
        hex = QString::fromStdString(wtx.GetHash().GetHex());
    }
Esempio n. 2
0
WalletModel::SendCoinsReturn WalletModel::sendCoins(const QList<SendCoinsRecipient> &recipients, const CCoinControl *coinControl)
{
    qint64 total = 0;
    QSet<QString> setAddress;
    QString hex;

    if(recipients.empty())
    {
        return OK;
    }

    if(isAnonymizeOnlyUnlocked())
    {
        return AnonymizeOnlyUnlocked;
    }

    // Pre-check input data for validity
    foreach(const SendCoinsRecipient &rcp, recipients)
    {
        if(!validateAddress(rcp.address))
        {
            return InvalidAddress;
        }
        setAddress.insert(rcp.address);

        if(rcp.amount <= 0)
        {
            return InvalidAmount;
        }
        total += rcp.amount;
    }

    if(recipients.size() > setAddress.size())
    {
        return DuplicateAddress;
    }

    int64_t nBalance = 0;
    std::vector<COutput> vCoins;
    wallet->AvailableCoins(vCoins, true, coinControl);

    BOOST_FOREACH(const COutput& out, vCoins)
        nBalance += out.tx->vout[out.i].nValue;

    if(total > nBalance)
    {
        return AmountExceedsBalance;
    }

    if((total + nTransactionFee) > nBalance)
    {
        return SendCoinsReturn(AmountWithFeeExceedsBalance, nTransactionFee);
    }

    {
        LOCK2(cs_main, wallet->cs_wallet);

        // Sendmany
        std::vector<std::pair<CScript, int64_t> > vecSend;
        foreach(const SendCoinsRecipient &rcp, recipients)
        {
            CScript scriptPubKey;
            scriptPubKey.SetDestination(CBitcoinAddress(rcp.address.toStdString()).Get());
            vecSend.push_back(make_pair(scriptPubKey, rcp.amount));
        }

        CWalletTx wtx;
        CReserveKey keyChange(wallet);
        int64_t nFeeRequired = 0;
        std::string strFailReason;

        bool fCreated = wallet->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired, strFailReason, coinControl);
 
        if(!fCreated)
        {
            if((total + nFeeRequired) > nBalance) // FIXME: could cause collisions in the future
            {
                return SendCoinsReturn(AmountWithFeeExceedsBalance, nFeeRequired);
            }
            return TransactionCreationFailed;
        }
        if(!uiInterface.ThreadSafeAskFee(nFeeRequired, tr("Sending...").toStdString()))
        {
            return Aborted;
        }
        if(!wallet->CommitTransaction(wtx, keyChange))
        {
            return TransactionCommitFailed;
        }
        hex = QString::fromStdString(wtx.GetHash().GetHex());
    }
Esempio n. 3
0
void System::layout2()
      {
      VBox* b = vbox();
      if (b) {
            b->layout();
            setbbox(b->bbox());
            return;
            }

      setPos(0.0, 0.0);
      QList<std::pair<int,SysStaff*>> visibleStaves;

      int firstStaffIdx        = -1;
      int lastStaffIdx         = 0;
      int firstStaffInitialIdx = -1;
      int lastStaffInitialIdx  = 0;
      Measure* fm              = firstMeasure();

      for (int i = 0; i < _staves.size(); ++i) {
            Staff*    s  = score()->staff(i);
            SysStaff* ss = _staves[i];
            if (s->show() && ss->show()) {
                  visibleStaves.append(std::pair<int,SysStaff*>(i, ss));
                  if (firstStaffIdx == -1)
                        firstStaffIdx = i;
                  if (i > lastStaffIdx)
                        lastStaffIdx = i;
                  if (fm && fm->visible(i)) {
                        if (firstStaffInitialIdx == -1)
                              firstStaffInitialIdx = i;
                        lastStaffInitialIdx = i;
                        }
                  }
            else {
                  ss->setbbox(QRectF());  // already done in layout() ?
                  }
            }
      if (firstStaffIdx == -1)
            firstStaffIdx = 0;
      if (firstStaffInitialIdx == -1)
            firstStaffInitialIdx = 0;

      qreal _spatium            = spatium();
      qreal y                   = 0.0;
      qreal minVerticalDistance = score()->styleP(StyleIdx::minVerticalDistance);
      qreal staffDistance       = score()->styleP(StyleIdx::staffDistance);
      qreal akkoladeDistance    = score()->styleP(StyleIdx::akkoladeDistance);

      if (visibleStaves.empty()) {
            qDebug("====no visible staves, staves %d, score staves %d", _staves.size(), score()->nstaves());
            }

      for (auto i = visibleStaves.begin();; ++i) {
            SysStaff* ss  = i->second;
            int si1       = i->first;
            Staff* staff  = score()->staff(si1);
            auto ni       = i + 1;

            qreal h = staff->height();
            if (ni == visibleStaves.end()) {
                  ss->setYOff(staff->lines() == 1 ? _spatium * staff->mag() : 0.0);
                  ss->bbox().setRect(_leftMargin, y, width() - _leftMargin, h);
                  break;
                  }

            int si2    = ni->first;
            qreal dist = h;

            switch (staff->innerBracket()) {
                  case BracketType::BRACE:
                        dist += akkoladeDistance;
                        break;
                  case BracketType::NORMAL:
                  case BracketType::SQUARE:
                  case BracketType::LINE:
                  case BracketType::NO_BRACKET:
                        dist += staffDistance;
                        break;
                  }
            dist += score()->staff(si2)->userDist();

            for (MeasureBase* mb : ml) {
                  if (!mb->isMeasure())
                        continue;
                  Measure* m = toMeasure(mb);
                  Shape& s1 = m->staffShape(si1);
                  Shape& s2 = m->staffShape(si2);

                  qreal d = s1.minVerticalDistance(s2) + minVerticalDistance;
                  dist    = qMax(dist, d);

                  Spacer* sp = m->mstaff(si1)->_vspacerDown;
                  if (sp) {
                        if (sp->spacerType() == SpacerType::FIXED) {
                              dist = staff->height() + sp->gap();
                              break;
                              }
                        else
                              dist = qMax(dist, staff->height() + sp->gap());
                        }
                  sp = m->mstaff(si2)->_vspacerUp;
                  if (sp)
                        dist = qMax(dist, sp->gap());
                  }

            ss->setYOff(staff->lines() == 1 ? _spatium * staff->mag() : 0.0);
            ss->bbox().setRect(_leftMargin, y, width() - _leftMargin, h);
            y += dist;
            }

      qreal systemHeight = staff(lastStaffIdx)->bbox().bottom();
      setHeight(systemHeight);

      for (MeasureBase* m : ml) {
            if (m->isMeasure()) {
                  // note that the factor 2 * _spatium must be corrected for when exporting
                  // system distance in MusicXML (issue #24733)
                  m->bbox().setRect(0.0, -_spatium, m->width(), systemHeight + 2.0 * _spatium);
                  }
            else if (m->isHBox()) {
                  m->bbox().setRect(0.0, 0.0, m->width(), systemHeight);
                  toHBox(m)->layout2();
                  }
            else if (m->isTBox()) {
//                  m->bbox().setRect(0.0, 0.0, m->width(), systemHeight);
                  toTBox(m)->layout();
                  }
            else
                  qDebug("unhandled measure type %s", m->name());
            }

      if (fm) {
            Segment* s        = fm->first();
            BarLine* _barLine = s->isBeginBarLineType() ? toBarLine(s->element(0)) : 0;

            if (_barLine) {
                  _barLine->setTrack(firstStaffInitialIdx * VOICES);
                  _barLine->setSpan(lastStaffInitialIdx - firstStaffInitialIdx + 1);
                  if (score()->staff(firstStaffInitialIdx)->lines() == 1)
                        _barLine->setSpanFrom(BARLINE_SPAN_1LINESTAFF_FROM);
                  else
                        _barLine->setSpanFrom(0);
                  int llines = score()->staff(lastStaffInitialIdx)->lines();
                  int spanTo = llines == 1 ? BARLINE_SPAN_1LINESTAFF_TO : (llines - 1) * 2;
                  _barLine->setSpanTo(spanTo);
                  _barLine->layout();
                  }
            }

      //---------------------------------------------------
      //  layout brackets vertical position
      //---------------------------------------------------

      for (Bracket* b : _brackets) {
            int staffIdx1 = b->firstStaff();
            int staffIdx2 = b->lastStaff();
            qreal sy = 0;                       // assume bracket not visible
            qreal ey = 0;
            // if start staff not visible, try next staff
            while (staffIdx1 <= staffIdx2 && !_staves[staffIdx1]->show())
                  ++staffIdx1;
            // if end staff not visible, try prev staff
            while (staffIdx1 <= staffIdx2 && !_staves[staffIdx2]->show())
                  --staffIdx2;
            // the bracket will be shown IF:
            // it spans at least 2 visible staves (staffIdx1 < staffIdx2) OR
            // it spans just one visible staff (staffIdx1 == staffIdx2) but it is required to do so
            // (the second case happens at least when the bracket is initially dropped)
            bool notHidden = (staffIdx1 < staffIdx2) || (b->span() == 1 && staffIdx1 == staffIdx2);
            if (notHidden) {                    // set vert. pos. and height to visible spanned staves
                  sy = _staves[staffIdx1]->bbox().top();
                  ey = _staves[staffIdx2]->bbox().bottom();
                  }
            b->rypos() = sy;
//            if (score()->staff(firstStaffInitialIdx)->lines() == 1)   // bbox of one line staff bad?
//                  b->rypos() -= _spatium;
            b->setHeight(ey - sy);
            b->layout();
            }

      //---------------------------------------------------
      //  layout instrument names
      //---------------------------------------------------

      int staffIdx = 0;

      for (Part* p : score()->parts()) {
            SysStaff* s = staff(staffIdx);
            SysStaff* s2;
            int nstaves = p->nstaves();
            if (s->show()) {
                  for (InstrumentName* t : s->instrumentNames) {
                        //
                        // override Text->layout()
                        //
                        qreal y1, y2;
                        switch (t->layoutPos()) {
                              default:
                              case 0:           // center at part
                                    y1 = s->bbox().top();
                                    s2 = staff(staffIdx);
                                    for (int i = staffIdx + nstaves - 1; i > 0; --i) {
                                          SysStaff* s = staff(i);
                                          if (s->show()) {
                                                s2 = s;
                                                break;
                                                }
                                          }
                                    y2 = s2->bbox().bottom();
                                    break;
                              case 1:           // center at first staff
                                    y1 = s->bbox().top();
                                    y2 = s->bbox().bottom();
                                    break;

                              // TODO:
                              // sort out invisible staves

                              case 2:           // center between first and second staff
                                    y1 = s->bbox().top();
                                    y2 = staff(staffIdx + 1)->bbox().bottom();
                                    break;
                              case 3:           // center at second staff
                                    y1 = staff(staffIdx + 1)->bbox().top();
                                    y2 = staff(staffIdx + 1)->bbox().bottom();
                                    break;
                              case 4:           // center between first and second staff
                                    y1 = staff(staffIdx + 1)->bbox().top();
                                    y2 = staff(staffIdx + 2)->bbox().bottom();
                                    break;
                              case 5:           // center at third staff
                                    y1 = staff(staffIdx + 2)->bbox().top();
                                    y2 = staff(staffIdx + 2)->bbox().bottom();
                                    break;
                              }
                        t->rypos() = y1 + (y2 - y1) * .5 + t->textStyle().offset(t->spatium()).y();
                        }
                  }
            staffIdx += nstaves;
            }
      }
Esempio n. 4
0
void TemplateOptionsWidget::templatePathSelectionChanged()
{
    const QList<QListWidgetItem *> selectedPaths = m_ui->m_templatePathListWidget->selectedItems();
    m_ui->m_removeTemplatePathButton->setEnabled(!selectedPaths.empty());
}
Esempio n. 5
0
void QgsPgTableModel::setSql( const QModelIndex &index, const QString &sql )
{
  if ( !index.isValid() || !index.parent().isValid() )
  {
    return;
  }

  //find out schema name and table name
  QModelIndex schemaSibling = index.sibling( index.row(), DbtmSchema );
  QModelIndex tableSibling = index.sibling( index.row(), DbtmTable );
  QModelIndex geomSibling = index.sibling( index.row(), DbtmGeomCol );

  if ( !schemaSibling.isValid() || !tableSibling.isValid() || !geomSibling.isValid() )
  {
    return;
  }

  QString schemaName = itemFromIndex( schemaSibling )->text();
  QString tableName = itemFromIndex( tableSibling )->text();
  QString geomName = itemFromIndex( geomSibling )->text();

  QList<QStandardItem *> schemaItems = findItems( schemaName, Qt::MatchExactly, DbtmSchema );
  if ( schemaItems.empty() )
  {
    return;
  }

  QStandardItem *schemaItem = schemaItems.at( DbtmSchema );

  int n = schemaItem->rowCount();
  for ( int i = 0; i < n; i++ )
  {
    QModelIndex currentChildIndex = indexFromItem( schemaItem->child( i, DbtmSchema ) );
    if ( !currentChildIndex.isValid() )
    {
      continue;
    }

    QModelIndex currentTableIndex = currentChildIndex.sibling( i, DbtmTable );
    if ( !currentTableIndex.isValid() )
    {
      continue;
    }

    QModelIndex currentGeomIndex = currentChildIndex.sibling( i, DbtmGeomCol );
    if ( !currentGeomIndex.isValid() )
    {
      continue;
    }

    if ( itemFromIndex( currentTableIndex )->text() == tableName && itemFromIndex( currentGeomIndex )->text() == geomName )
    {
      QModelIndex sqlIndex = currentChildIndex.sibling( i, DbtmSql );
      if ( sqlIndex.isValid() )
      {
        itemFromIndex( sqlIndex )->setText( sql );
        break;
      }
    }
  }
}
bool QgsPointDistanceRenderer::renderFeature( QgsFeature& feature, QgsRenderContext& context, int layer, bool selected, bool drawVertexMarker )
{
  Q_UNUSED( drawVertexMarker );
  Q_UNUSED( context );
  Q_UNUSED( layer );

  //check if there is already a point at that position
  if ( !feature.hasGeometry() )
    return false;

  QgsMarkerSymbol* symbol = firstSymbolForFeature( feature, context );

  //if the feature has no symbol (eg, no matching rule in a rule-based renderer), skip it
  if ( !symbol )
    return false;

  //point position in screen coords
  QgsGeometry geom = feature.geometry();
  QgsWkbTypes::Type geomType = geom.wkbType();
  if ( QgsWkbTypes::flatType( geomType ) != QgsWkbTypes::Point )
  {
    //can only render point type
    return false;
  }

  QString label;
  if ( mDrawLabels )
  {
    label = getLabel( feature );
  }

  QgsCoordinateTransform xform = context.coordinateTransform();
  QgsFeature transformedFeature = feature;
  if ( xform.isValid() )
  {
    geom.transform( xform );
    transformedFeature.setGeometry( geom );
  }

  double searchDistance = mTolerance * QgsSymbolLayerUtils::mapUnitScaleFactor( context, mToleranceUnit, mToleranceMapUnitScale );
  QgsPoint point = transformedFeature.geometry().asPoint();
  QList<QgsFeatureId> intersectList = mSpatialIndex->intersects( searchRect( point, searchDistance ) );
  if ( intersectList.empty() )
  {
    mSpatialIndex->insertFeature( transformedFeature );
    // create new group
    ClusteredGroup newGroup;
    newGroup << GroupedFeature( transformedFeature, symbol, selected, label );
    mClusteredGroups.push_back( newGroup );
    // add to group index
    mGroupIndex.insert( transformedFeature.id(), mClusteredGroups.count() - 1 );
    mGroupLocations.insert( transformedFeature.id(), point );
  }
  else
  {
    // find group with closest location to this point (may be more than one within search tolerance)
    QgsFeatureId minDistFeatureId = intersectList.at( 0 );
    double minDist = mGroupLocations.value( minDistFeatureId ).distance( point );
    for ( int i = 1; i < intersectList.count(); ++i )
    {
      QgsFeatureId candidateId = intersectList.at( i );
      double newDist = mGroupLocations.value( candidateId ).distance( point );
      if ( newDist < minDist )
      {
        minDist = newDist;
        minDistFeatureId = candidateId;
      }
    }

    int groupIdx = mGroupIndex[ minDistFeatureId ];
    ClusteredGroup& group = mClusteredGroups[groupIdx];

    // calculate new centroid of group
    QgsPoint oldCenter = mGroupLocations.value( minDistFeatureId );
    mGroupLocations[ minDistFeatureId ] = QgsPoint(( oldCenter.x() * group.size() + point.x() ) / ( group.size() + 1.0 ),
                                          ( oldCenter.y() * group.size() + point.y() ) / ( group.size() + 1.0 ) );

    // add to a group
    group << GroupedFeature( transformedFeature, symbol, selected, label );
    // add to group index
    mGroupIndex.insert( transformedFeature.id(), groupIdx );
  }

  return true;
}
Esempio n. 7
0
WalletModel::SendCoinsReturn WalletModel::prepareTransaction(WalletModelTransaction &transaction, const CCoinControl *coinControl)
{
    qint64 total = 0;
    QList<SendCoinsRecipient> recipients = transaction.getRecipients();
    std::vector<std::pair<CScript, int64_t> > vecSend;

    if(recipients.empty())
    {
        return OK;
    }

    QSet<QString> setAddress; // Used to detect duplicates
    int nAddresses = 0;

    // Pre-check input data for validity
    foreach(const SendCoinsRecipient &rcp, recipients)
    {
        if (rcp.paymentRequest.IsInitialized())
        {   // PaymentRequest...
            int64_t subtotal = 0;
            const payments::PaymentDetails& details = rcp.paymentRequest.getDetails();
            for (int i = 0; i < details.outputs_size(); i++)
            {
                const payments::Output& out = details.outputs(i);
                if (out.amount() <= 0) continue;
                subtotal += out.amount();
                const unsigned char* scriptStr = (const unsigned char*)out.script().data();
                CScript scriptPubKey(scriptStr, scriptStr+out.script().size());
                vecSend.push_back(std::pair<CScript, int64_t>(scriptPubKey, out.amount()));
            }
            if (subtotal <= 0)
            {
                return InvalidAmount;
            }
            total += subtotal;
        }
        else
        {   // User-entered bitcoin address / amount:
            if(!validateAddress(rcp.address))
            {
                return InvalidAddress;
            }
            if(rcp.amount <= 0)
            {
                return InvalidAmount;
            }
            setAddress.insert(rcp.address);
            ++nAddresses;

            CScript scriptPubKey;
            scriptPubKey.SetDestination(CBitcoinAddress(rcp.address.toStdString()).Get());
            vecSend.push_back(std::pair<CScript, int64_t>(scriptPubKey, rcp.amount));

            total += rcp.amount;
        }
    }
    if(setAddress.size() != nAddresses)
    {
        return DuplicateAddress;
    }

    qint64 nBalance = getBalance(coinControl);

    if(total > nBalance)
    {
        return AmountExceedsBalance;
    }

    if((total + nTransactionFee) > nBalance)
    {
        transaction.setTransactionFee(nTransactionFee);
        return SendCoinsReturn(AmountWithFeeExceedsBalance);
    }

    {
        LOCK2(cs_main, wallet->cs_wallet);

        transaction.newPossibleKeyChange(wallet);
        int64_t nFeeRequired = 0;
        std::string strFailReason;

        CWalletTx *newTx = transaction.getTransaction();
        CReserveKey *keyChange = transaction.getPossibleKeyChange();
        bool fCreated = wallet->CreateTransaction(vecSend, *newTx, *keyChange, nFeeRequired, strFailReason, coinControl);
        transaction.setTransactionFee(nFeeRequired);

        if(!fCreated)
        {
            if((total + nFeeRequired) > nBalance)
            {
                return SendCoinsReturn(AmountWithFeeExceedsBalance);
            }
            emit message(tr("Send Coins"), QString::fromStdString(strFailReason),
                         CClientUIInterface::MSG_ERROR);
            return TransactionCreationFailed;
        }
    }

    return SendCoinsReturn(OK);
}
Esempio n. 8
0
SPuzzleTrace *CBDTracer<OpenListType>::trace( const int depthLimit,
                                const bool iterativeDeepening,
                                const bool graphSearch,
                                const CPuzzleGraphModel *graph ) const
{
    bool goalFound = false;
    int openNoForward  = 0;
    int evalNoForward  = 1 + 1*graphSearch;
    int openNoBackward = 2 + 1*graphSearch;
    int evalNoBackward = 3 + 2*graphSearch;
    int depth;

    //if( graphSearch ) evalNo++;
    SPuzzleTrace *newTrace = new SPuzzleTrace;

    if( graph->getStartNode() == NULL ) return newTrace;

    newTrace->s_aiName = "name";
    newTrace->s_columnNames.append("open");
    if( graphSearch ) newTrace->s_columnNames.append("closed");
    newTrace->s_columnNames.append("eval");

    newTrace->s_columnNames.append("open");
    if( graphSearch ) newTrace->s_columnNames.append("closed");
    newTrace->s_columnNames.append("eval");

    newTrace->s_columnNames.append("");

    if(iterativeDeepening)
        depth = 0;
    else
        depth = depthLimit;

    while(depth <= depthLimit && !goalFound)
    {
        SPuzzleCall *curDepth = new SPuzzleCall;
        OpenListType openForward, openBackward;
        CClosedList closedForward, closedBackward;
        CSATraceNode evalNodeForward, evalNodeBackward;
        bool exaustedForward = false;
        bool exaustedBackward = false;




        QList<SPuzzleNode *> goals = graph->getGoalNodeList();

        QList< CSATraceNode > historyForward;
        QList< CSATraceNode > historyBackward;

        if(goals.empty())
        {
            curDepth->s_comment = "Cannot commence bi-directional search - no goals";
            newTrace->s_depths.append( curDepth );
            return newTrace;
        }
        openForward.push( CSATraceNode( graph->getStartNode() ) );
        openBackward.push( CSATraceNode( goals.first() ) );
        for(;;)
        {
            SBDLine *curLine = new SBDLine;

            if(exaustedForward)
            {
                curLine->s_strings.append( QString() ); // open
                curLine->s_strings.append( QString() ); // eval
                if( graphSearch )
                    curLine->s_strings.append( QString() ); // closed
                goto backward;
            }

            ////////////////////////////////////////////
            // Forward Search
            ////////////////////////////////////////////

            evalNodeForward = openForward.top();

            curLine->s_strings.append( openForward.getString() );

            if( graphSearch ) curLine->s_strings.append( closedForward.getString() );

            curLine->s_strings.append( openForward.getEvalString() );
            historyForward.append( evalNodeForward );


            if( historyBackward.contains( evalNodeForward ) )
            {
                // GOAL FOUND!
                goalFound = true;
                // Add relevant comment and break out of loop
                //curLine->s_strings.append(
                 //goalString(graph, curDepth->s_lines, evalNode, openNo, evalNo) );
                int index = historyBackward.indexOf( evalNodeForward );

                int cost = evalNodeForward.getCost() +  historyBackward[index].getCost();

                // Midpoint may have different
                curDepth->s_lines.append( curLine );

                curDepth->s_comment =
                    goalString(graph, curDepth->s_lines, curDepth->s_lines.size()-1, index , cost,
                               openNoForward, evalNoForward, openNoBackward, evalNoBackward);

                    /*int numStrings = curLine->s_strings.size();
                    for(int i=0; i<numStrings; i++)
                        curLine->s_strings.append( QString() );
                */


                break;
            }


            //curLine->s_strings.append(""); // add blank comment;

            // Remove eval node from front of open list.
            openForward.pop();

            // Push all of eval node's children onto open list,
            // with given depth limit. Strip away any nodes that
            // are on the closed list.
            openForward.push(
                closedForward.strip(
                    evalNodeForward.expand(depth) ) );

            if( openForward.empty() )
            {
                if( exaustedBackward )
                {
                    curDepth->s_lines.append( curLine );
                    curDepth->s_comment = "search completed and no goal found";
                    break;
                }
                else
                {
                    exaustedForward = true;
                }
            }

            if( graphSearch ) closedForward.push(evalNodeForward);




backward:
            if(exaustedBackward)
            {
                curDepth->s_lines.append( curLine );
                continue;
            }
            ////////////////////////////////////////////
            // Backward Search
            ////////////////////////////////////////////

            evalNodeBackward = openBackward.top();

            curLine->s_strings.append( openBackward.getString() );

            if( graphSearch ) curLine->s_strings.append( closedBackward.getString() );

            curLine->s_strings.append( openBackward.getEvalString() );

            historyBackward.append( evalNodeBackward );

            curDepth->s_lines.append( curLine );

            if( historyForward.contains( evalNodeBackward ) )
            {
                // GOAL FOUND!
                goalFound = true;
                // Add relevant comment and break out of loop
                int index = historyForward.indexOf( evalNodeBackward );

                int cost = evalNodeBackward.getCost() +  historyForward[index].getCost();

                curDepth->s_comment =
                    goalString(graph, curDepth->s_lines, index, curDepth->s_lines.size()-1, cost,
                               openNoForward, evalNoForward, openNoBackward, evalNoBackward);
                break;
            }

            if( !graphSearch && curDepth->s_lines.count() > 30)
            {
                curDepth->s_comment = "Ad Infinitum";
                break;
            }
            //curLine->s_strings.append(""); // add blank comment;

            // Remove eval node from front of open list.
            openBackward.pop();

            // Push all of eval node's children onto open list,
            // with given depth limit. Strip away any nodes that
            // are on the closed list.
            openBackward.push(
                closedBackward.strip(
                    evalNodeBackward.expandBackward(depth) ) );

            if( openBackward.empty() )
            {
                if( exaustedForward )
                {
                    curDepth->s_comment = "search completed and no goal found";
                    break;
                }
                else
                {
                    exaustedBackward = true;
                }
            }

            if( graphSearch ) closedBackward.push(evalNodeBackward);

        }
        newTrace->s_depths.append( curDepth );
        depth++;
    }



    return newTrace;
}
Esempio n. 9
0
void QgsLocator::fetchResults( const QString &string, const QgsLocatorContext &c, QgsFeedback *feedback )
{
  QgsLocatorContext context( c );
  // ideally this should not be required, as well behaved callers
  // will NOT fire up a new fetchResults call while an existing one is
  // operating/waiting to be canceled...
  cancelRunningQuery();

  // if no feedback object was passed, create one that is owned by this object
  // to ensure that filters ALWAYS receive a valid feedback
  if ( !feedback )
  {
    mOwnedFeedback.reset( new QgsFeedback() );
    feedback = mOwnedFeedback.get();
  }
  else
  {
    mOwnedFeedback.reset( nullptr );
  }
  mFeedback = feedback;

  QList< QgsLocatorFilter * > activeFilters;
  QString searchString = string;
  QString prefix = searchString.left( std::max( searchString.indexOf( ' ' ), 0 ) );
  if ( !prefix.isEmpty() )
  {
    for ( QgsLocatorFilter *filter : qgis::as_const( mFilters ) )
    {
      if ( filter->activePrefix() == prefix && filter->enabled() )
      {
        activeFilters << filter;
      }
    }
    context.usingPrefix = !activeFilters.empty();
  }
  if ( !activeFilters.isEmpty() )
  {
    searchString = searchString.mid( prefix.length() + 1 );
  }
  else
  {
    for ( QgsLocatorFilter *filter : qgis::as_const( mFilters ) )
    {
      if ( filter->useWithoutPrefix() && filter->enabled() )
      {
        activeFilters << filter;
      }
    }
  }

  QList< QgsLocatorFilter *> threadedFilters;
  for ( QgsLocatorFilter *filter : qgis::as_const( activeFilters ) )
  {
    filter->clearPreviousResults();
    std::unique_ptr< QgsLocatorFilter > clone( filter->clone() );
    connect( clone.get(), &QgsLocatorFilter::resultFetched, clone.get(), [this, filter]( QgsLocatorResult result )
    {
      result.filter = filter;
      emit filterSentResult( result );
    } );
    clone->prepare( searchString, context );

    if ( clone->flags() & QgsLocatorFilter::FlagFast )
    {
      // filter is fast enough to fetch results on the main thread
      clone->fetchResults( searchString, context, feedback );
    }
    else
    {
      // run filter in background
      threadedFilters.append( clone.release() );
    }
  }

  mActiveThreads.clear();
  for ( QgsLocatorFilter *filter : qgis::as_const( threadedFilters ) )
  {
    QThread *thread = new QThread();
    mActiveThreads.append( thread );
    filter->moveToThread( thread );
    connect( thread, &QThread::started, filter, [filter, searchString, context, feedback]
    {
      if ( !feedback->isCanceled() )
        filter->fetchResults( searchString, context, feedback );
      filter->emit finished();
    }, Qt::QueuedConnection );
    connect( filter, &QgsLocatorFilter::finished, thread, &QThread::quit );
    connect( filter, &QgsLocatorFilter::finished, filter, &QgsLocatorFilter::deleteLater );
    connect( thread, &QThread::finished, thread, [this, thread]
    {
      mActiveThreads.removeAll( thread );
      if ( mActiveThreads.empty() )
        emit finished();
    } );
    connect( thread, &QThread::finished, thread, &QThread::deleteLater );
    thread->start();
  }

  if ( mActiveThreads.empty() )
    emit finished();
}
Esempio n. 10
0
bool RemoveBiasOperator::applyOperator(Individual *individual, CommandExecutor*) {

	NeuralNetwork *net = dynamic_cast<NeuralNetwork*>(individual->getGenome());

	if(net == 0) {
		Core::log("RemoveBiasOperator: Could not apply operator because individual did not "
				  "provide a NeuralNetwork as genome!");
		return false;
	}

	QString generationDate = QString::number(Evolution::getEvolutionManager()
				->getCurrentGenerationValue()->get());

	QList<Neuron*> neurons = net->getNeurons();
	QList<Neuron*> consideredNeurons = neurons;

	//remove protected neurons and neurons without bias values.
	{
		for(QListIterator<Neuron*> i(neurons); i.hasNext();) {
			Neuron *neuron = i.next();

			if(neuron->getBiasValue().get() == 0.0) {
				consideredNeurons.removeAll(neuron);
				continue;
			}
			if(neuron->hasProperty(NeuralNetworkConstants::TAG_ELEMENT_PROTECTED)) {
				consideredNeurons.removeAll(neuron);
				continue;
			}
			if(neuron->hasProperty(NeuralNetworkConstants::TAG_NEURON_PROTECT_BIAS_EXISTENCE)) {
				consideredNeurons.removeAll(neuron);
				continue;
			}
			else if(neuron->hasProperty(NeuralNetworkConstants::TAG_NEURON_PROTECT_BIAS)) {
				consideredNeurons.removeAll(neuron);
				continue;
			}
		}
	}

	double probability = mRemoveProbability->get();
	int maxNumberOfRemovedBiases = mMaximalNumberOfRemovedBiases->get();

	for(int i = 0; i < maxNumberOfRemovedBiases && !consideredNeurons.empty(); ++i) {
		
		if(Random::nextDouble() >= probability) {
			continue;
		}

		Neuron *neuron = consideredNeurons.value(Random::nextInt(consideredNeurons.size()));

		if(neuron == 0) {
			continue;
		}

		consideredNeurons.removeAll(neuron);
		neuron->getBiasValue().set(0.0);

		neuron->setProperty(NeuralNetworkConstants::PROP_ELEMENT_MODIFIED);

		//mark the individual as significantly modified
		individual->setProperty(EvolutionConstants::TAG_GENOME_SIGNIFICANT_CHANGE,
						generationDate);
		
		individual->setProperty(EvolutionConstants::TAG_GENOME_CHANGE_SUMMARY,
						individual->getProperty(EvolutionConstants::TAG_GENOME_CHANGE_SUMMARY) 
							+ ",N:" + QString::number(neuron->getId()) + ":rB"); 
	}

	return true;
}
Esempio n. 11
0
void KEquityPriceUpdateDlg::slotReceivedQuote(const QString& _id, const QString& _symbol, const QDate& _date, const double& _price)
{
  QList<QTreeWidgetItem*> foundItems = lvEquityList->findItems(_id, Qt::MatchExactly, ID_COL);
  QTreeWidgetItem* item = 0;

  if (! foundItems.empty())
    item = foundItems.at(0);

  QTreeWidgetItem* next = 0;

  if (item) {
    if (_price > 0.0f && _date.isValid()) {
      QDate date = _date;
      if (date > QDate::currentDate())
        date = QDate::currentDate();

      double price = _price;
      QString id = _id.toUtf8();
      MyMoneySecurity sec;
      if (_id.contains(" ") == 0) {
        MyMoneySecurity security = MyMoneyFile::instance()->security(id);
        QString factor = security.value("kmm-online-factor");
        if (!factor.isEmpty()) {
          price *= MyMoneyMoney(factor).toDouble();
        }
        try {
          sec = MyMoneyFile::instance()->security(id);
          sec = MyMoneyFile::instance()->security(sec.tradingCurrency());
        } catch (const MyMoneyException &) {
          sec = MyMoneySecurity();
        }

      } else {
        QRegExp splitrx("([0-9a-z\\.]+)[^a-z0-9]+([0-9a-z\\.]+)", Qt::CaseInsensitive);
        if (splitrx.indexIn(_id) != -1) {
          try {
            sec = MyMoneyFile::instance()->security(splitrx.cap(2).toUtf8());
          } catch (const MyMoneyException &) {
            sec = MyMoneySecurity();
          }
        }
      }
      item->setText(PRICE_COL, KGlobal::locale()->formatMoney(price, sec.tradingSymbol(), KMyMoneyGlobalSettings::pricePrecision()));
      item->setText(DATE_COL, date.toString(Qt::ISODate));
      logStatusMessage(i18n("Price for %1 updated (id %2)", _symbol, _id));
      // make sure to make OK button available
      btnOK->setEnabled(true);
    } else {
      logErrorMessage(i18n("Received an invalid price for %1, unable to update.", _symbol));
    }

    prgOnlineProgress->setValue(prgOnlineProgress->value() + 1);
    item->setSelected(false);

    // launch the NEXT one ... in case of m_fUpdateAll == false, we
    // need to parse the list to find the next selected one
    next = lvEquityList->invisibleRootItem()->child(lvEquityList->invisibleRootItem()->indexOfChild(item) + 1);
    if (!m_fUpdateAll) {
      while (next && !next->isSelected()) {
        prgOnlineProgress->setValue(prgOnlineProgress->value() + 1);
        next = lvEquityList->invisibleRootItem()->child(lvEquityList->invisibleRootItem()->indexOfChild(next) + 1);
      }
    }
  } else {
    logErrorMessage(i18n("Received a price for %1 (id %2), but this symbol is not on the list. Aborting entire update.", _symbol, _id));
  }

  if (next) {
    m_webQuote.launch(next->text(SYMBOL_COL), next->text(ID_COL), next->text(SOURCE_COL));
  } else {
    finishUpdate();
  }
}
Esempio n. 12
0
/*----------------------------------*
 * Méthode traitement de la trame   *
 *----------------------------------*/
bool Ihm::traitementTrame(QString trame){

    //témoin timer affichage
    if (ui->lbActivite->isEnabled())
        ui->lbActivite->setEnabled(false);
    else
        ui->lbActivite->setEnabled(true);
//qDebug() << "[1] dans traitement";

    //décodage trame
    QString num_badge, sens, mouvement, num_lecteur;

    //séparation des parties de la trame
    num_badge = trame.mid(3,3); //numéro de badge

    //suppression mauvais badge
    if(num_badge == "000") {
        qDebug("Mauvais badge.");
        //obtenir date
        QString date = QDateTime::currentDateTime().toString();
        ui->txtAlarme->textCursor().insertText(date+"<Erreur> Mauvais badge num=000\n");
        curseur.setPosition(position); // Replacement du curseur à l'endroit où il se trouvait
        ui->txtAlarme->setTextCursor(curseur); // Application du curseur à la zone de texte
        return false;
    }

    sens = trame.mid(1,2); //niveau de réception du tag
    mouvement = trame.mid(6,3); //niveau de mouvement mesuré
    num_lecteur = trame.mid(9,2);   //numéro du lecteur

    //conversion des valeurs en int à partir de ASCII hexa et mise à l'échelle
    //c'est-Ã -dire conversion de l'hexadécimal en décimal
    int num_badge_i = num_badge.toInt(0,16);
    int sens_i = sens.toInt(0,16);
    int num_lecteur_i = num_lecteur.toInt(0,16);
    int mouvement_i = mouvement.toInt(0,16);

    //si le badge n'existe pas dans la BDD
    if(!pBdd->badgeExiste(num_badge)){
        //obtenir date
        QString date = QDateTime::currentDateTime().toString();
        ui->txtAlarme->textCursor().insertText(date+"<Erreur><Badge "+num_badge+QString::fromUtf8("> Badge inconnu  dans la Base de données\n"));
        curseur.setPosition(position); // Replacement du curseur à l'endroit où il se trouvait
        ui->txtAlarme->setTextCursor(curseur); // Application du curseur à la zone de texte
        return false;
    }

    //badge n'existe pas sur l'IHM
    if(!pDynamique.BadgeActif[num_badge_i]){

        //Historique des événements (log) : nouveau badge
        pBdd->setLog(1, num_badge_i);    //1=nouveau badge

        tll = new T_ListeLabel();

        for(int i=0 ; i<MAXLECTEURS ; i++){   // init à 100
            for(int j=0 ; j<MAXVAL ; j++){
                tll->moySens[i][j]=100;
            }
        }
        for(int i=0 ; i<MAXLECTEURS ; i++){
            tll->sdp[i]=0;      //sens de passage
            tll->sdpMem[i]=0;
        }
        memset(tll->indMoy, 0, sizeof(tll->indMoy));    //init à 0

        //obtenir vue(s) en fonction du lecteur
        //déclaration QList
        QList<T_TupleLecteurS> listeTupleL;

        pBdd->getVueFctLect(num_lecteur_i, &listeTupleL);

        //récupération des infos dans la liste
        if (!listeTupleL.empty()){
            for (int i = 0; i < listeTupleL.count(); i++) {

                int num_vue = listeTupleL.at(i).num_vue;

                //se placer sur l'onglet
                QWidget *onglet;
                onglet = pDynamique.onglet[num_vue];

                //nouveau label dynamique pour un badge
                tll->labelB[num_vue][num_badge_i] = new QLabel(onglet);

                //The object will be deleted when control returns to the event loop.//ps: j'aime bien ce commentaire !
                connect (tll->labelB[num_vue][num_badge_i], SIGNAL(destroyed()), tll->labelB[num_vue][num_badge_i], SLOT(deleteLater()));

                //sauvegarde de ce label dans Dynamique
                pDynamique.labelB[num_vue][num_badge_i] = tll->labelB[num_vue][num_badge_i];
//qDebug() << pDynamique.labelB[num_vue][num_badge_i];
                //réglage par défaut du nouveau badge
                tll->labelB[num_vue][num_badge_i]->setPixmap(QPixmap("ressources/DefaultConfigure.png"));
                tll->labelB[num_vue][num_badge_i]->setGeometry(590, 620, 20, 20); // largeur hauteur à définir
            }
        }

        tll->numBadge = num_badge_i;        //numéro de badge
        tll->numLecteur = num_lecteur_i;    //numéro de lecteur
        tll->etat = 0;                      //aller

        // réglage du timer associé au mouvement
        tll->tpsMouv = new QTimer(this);                                    //nouveau Timer
        connect(tll->tpsMouv, SIGNAL(timeout()), this, SLOT(timerMouv()));  //connect timeout
        tll->tpsMouv->setSingleShot(true);                                  //un seul temps
        tll->tpsMouv->start(this->tempoM);                                  //débute le timer

        // réglage du timer associé à la réception
        tll->tpsSens[num_lecteur_i] = new QTimer(this);                                     //nouveau Timer
        connect(tll->tpsSens[num_lecteur_i], SIGNAL(timeout()), this, SLOT(timerRec()));   //connect timeout
        tll->tpsSens[num_lecteur_i]->setSingleShot(true);                                   //un seul temps
        tll->tpsSens[num_lecteur_i]->start(this->tempoR);                                   //débute le timer

        // ajout à la liste mémoire
        listeLabel.append(tll);

        //maintenant le badge existe sur l'IHM donc le sauvegarder
        pDynamique.BadgeActif[num_badge_i] = true;

    }

    tll->numLecteur = num_lecteur_i;    //sauvegarde numéro lecteur

    tll->etat |= MOUV0;   // mouv=0
//modif
   // tll->etat ^= MOUV0;
    //relance du timer si mouvement
    if (mouvement_i > 0 ) {  // si mouvement
        tll->etat &= ~MOUV;    // alarme mouvement
        tll->etat &= ~MOUV0;   // un seul mouvement
        tll->tpsMouv->setSingleShot(true);
        tll->tpsMouv->start(this->tempoM);  //ms
    }

    // réarmer le timer REC, le créer si nouveau lecteur
    tll->etat &= ~REC;
    //création timer réception, si nouveau lecteur
    if (!tll->tpsSens[num_lecteur_i]) {
        tll->tpsSens[num_lecteur_i] = new QTimer(this);
        connect(tll->tpsSens[num_lecteur_i], SIGNAL(timeout()), this, SLOT(TimerRec()));
    }
    //réarmer le timer de réception
    tll->tpsSens[num_lecteur_i]->setSingleShot(true);
    tll->tpsSens[num_lecteur_i]->start(this->tempoR);


    //déclaration QList
    QList<T_Personne > listePersonne;

    //Recherche identité de la personne
    int num_pers = pBdd->badgeIdentite(num_badge_i, &listePersonne);
    if (num_pers == -1){
        //le badge n'est pas lié avec une personne
        //obtenir date
        QString date = QDateTime::currentDateTime().toString();
        ui->txtAlarme->textCursor().insertText(date+"<Erreur><Badge "+num_badge+QString::fromUtf8("> Badge non lié à une personne\n"));
        curseur.setPosition(position); // Replacement du curseur à l'endroit où il se trouvait
        ui->txtAlarme->setTextCursor(curseur); // Application du curseur à la zone de texte
    } else {
        tll->nom[num_pers] = listePersonne.at(0).nom;
        tll->prenom[num_pers] = listePersonne.at(0).prenom;
        tll->societe[num_pers] = listePersonne.at(0).societe;
        tll->photo[num_pers] = listePersonne.at(0).photo;
    }


    // calcul de la moyenne de la sensibilité
    tll->moySens[num_lecteur_i][tll->indMoy[num_lecteur_i]++] = sens_i ;

    if (tll->indMoy[num_lecteur_i] == MAXVAL){
        tll->indMoy[num_lecteur_i] = 0;     //indice du tableau de moyenne
    }
    int moy = 0;
    moy = calculerMoyenne(tll);     //sur MAXVAL valeur
    tll->sdp[num_lecteur_i] = moy;  //mémo pour calcul sens de passage
    moy -= 100;

    if (!sensDePassage(tll)){ //maj de zone et du sens de passage de ce badge
        //pas de sens de passage
        qDebug("pas de sens de passage dans BDD");
        //obtenir date
        QString date = QDateTime::currentDateTime().toString();
        ui->txtAlarme->textCursor().insertText(date +"<Erreur><Lecteur "+num_lecteur+ QString::fromUtf8("> Pas de sens de passage précisé dans la Base de Données\n"));
        curseur.setPosition(position); // Replacement du curseur à l'endroit où il se trouvait
        ui->txtAlarme->setTextCursor(curseur); // Application du curseur à la zone de texte
        return false;
    }

    // recherche si lecteur n'est pas connecté
    if (!pBdd->getEtatLect(num_lecteur_i)){
        qDebug("le lecteur n'est pas connecte ?!");
        //obtenir date
        QString date = QDateTime::currentDateTime().toString();
        ui->txtAlarme->textCursor().insertText(date+"<Erreur><Lecteur "+num_lecteur+QString::fromUtf8("> Lecteur non connecté\n"));
        curseur.setPosition(position); // Replacement du curseur à l'endroit où il se trouvait
        ui->txtAlarme->setTextCursor(curseur); // Application du curseur à la zone de texte
        return false;
    }

    //Obtenir les points de la zone en fonction des vues
//qDebug() << "[2] avant placement";
    //obtenir vue(s) en fonction du lecteur
    //déclaration QList
    QList<T_TupleLecteurS> listeTupleL;

    pBdd->getVueFctLect(num_lecteur_i, &listeTupleL);

    if (!listeTupleL.empty()){
        for (int i = 0; i < listeTupleL.count(); i++) {

            int num_vue = listeTupleL.at(i).num_vue;

            pBdd->getPointsZone(num_vue, tll->zone, &tll->ptA, &tll->ptB);

            this->calculerDroite(moy, tll->ptA, tll->ptB, &tll->ptBadge[num_vue]);

           // tll = listeLabel.at(num_badge_i);
            //affichage
           // tll->labelB[num_vue][num_badge_i]->setEnabled(true);
           // tll->labelB[num_vue][num_badge_i]->setVisible(true);
            pDynamique.labelB[num_vue][num_badge_i]->setVisible(true);


//qDebug() << "[3] avant état";
            //en fonction de l'état
            switch(tll->etat) {
            case 0:  // ALLER
                if (num_vue == 1 || tll->zone == -1){
                    //pas de sens de passage
                    pDynamique.labelB[num_vue][num_badge_i]->setPixmap(QPixmap("ressources/pers_vert.jpg"));
                } else {
                    pDynamique.labelB[num_vue][num_badge_i]->setPixmap(QPixmap("ressources/haut_vert.jpg"));
                }
                break;
            case 1:
                if (num_vue == 1 || tll->zone == -1){
                    //pas de sens de passage
                    pDynamique.labelB[num_vue][num_badge_i]->setPixmap(QPixmap("ressources/pers_rouge.jpg"));
                } else {
                    pDynamique.labelB[num_vue][num_badge_i]->setPixmap(QPixmap("ressources/haut_rouge.jpg"));
                }
                //homme en danger
                emit signalHommeEnDanger(tll->nom[num_pers]);
                //Historique des événements (log) : alarme mouvement
                pBdd->setLog(3, num_badge_i);    //3=alarme mouvement
                break;
            case 2:
                pDynamique.labelB[num_vue][num_badge_i]->setEnabled(false);
                break;
            case 3:
                pDynamique.labelB[num_vue][num_badge_i]->setEnabled(false);
                break;
            case 4:
                if (num_vue == 1 || tll->zone == -1){
                    //pas de sens de passage
                    pDynamique.labelB[num_vue][num_badge_i]->setPixmap(QPixmap("ressources/pers_vert.jpg"));
                } else {
                    pDynamique.labelB[num_vue][num_badge_i]->setPixmap(QPixmap("ressources/bas_vert.jpg"));
                }
                break;
            case 5:
                if (num_vue == 1 || tll->zone == -1){
                    //pas de sens de passage
                    pDynamique.labelB[num_vue][num_badge_i]->setPixmap(QPixmap("ressources/pers_rouge.jpg"));
                } else {
                    pDynamique.labelB[num_vue][num_badge_i]->setPixmap(QPixmap("ressources/bas_rouge.jpg"));
                }
                //homme en danger
                emit signalHommeEnDanger(tll->nom[num_pers]);
                //Historique des événements (log) : alarme mouvement
                pBdd->setLog(3, num_badge_i);    //3=alarme mouvement
                break;
            case 6:
                pDynamique.labelB[num_vue][num_badge_i]->setEnabled(false);
                break;
            case 7:
                pDynamique.labelB[num_vue][num_badge_i]->setEnabled(false);
                break;
            case 8:
                if (num_vue == 1 || tll->zone == -1){
                    //pas de sens de passage
                    pDynamique.labelB[num_vue][num_badge_i]->setPixmap(QPixmap("ressources/pers_orange.jpg"));
                } else {
                    pDynamique.labelB[num_vue][num_badge_i]->setPixmap(QPixmap("ressources/haut_orange.jpg"));
                }
                break;
            case 9:
                if (num_vue == 1 || tll->zone == -1){
                    //pas de sens de passage
                    pDynamique.labelB[num_vue][num_badge_i]->setPixmap(QPixmap("ressources/pers_rouge.jpg"));
                } else {
                    pDynamique.labelB[num_vue][num_badge_i]->setPixmap(QPixmap("ressources/haut_rouge.jpg"));
                }
                //homme en danger
                emit signalHommeEnDanger(tll->nom[num_pers]);
                //Historique des événements (log) : alarme mouvement
                pBdd->setLog(3, num_badge_i);    //3=alarme mouvement
                break;
            case 10:
                pDynamique.labelB[num_vue][num_badge_i]->setEnabled(false);
                break;
            case 11:
                pDynamique.labelB[num_vue][num_badge_i]->setEnabled(false);
                break;
            case 12:
                if (num_vue == 1 || tll->zone == -1){
                    //pas de sens de passage
                    pDynamique.labelB[num_vue][num_badge_i]->setPixmap(QPixmap("ressources/pers_orange.jpg"));
                } else {
                    pDynamique.labelB[num_vue][num_badge_i]->setPixmap(QPixmap("ressources/bas_orange.jpg"));
                }
                break;
            case 13:
                if (num_vue == 1 || tll->zone == -1){
                    //pas de sens de passage
                    pDynamique.labelB[num_vue][num_badge_i]->setPixmap(QPixmap("ressources/pers_rouge.jpg"));
                } else {
                    pDynamique.labelB[num_vue][num_badge_i]->setPixmap(QPixmap("ressources/bas_rouge.jpg"));
                }
                //homme en danger
                emit signalHommeEnDanger(tll->nom[num_pers]);
                //Historique des événements (log) : alarme mouvement
                pBdd->setLog(3, num_badge_i);    //3=alarme mouvement
                break;
            case 14:
                pDynamique.labelB[num_vue][num_badge_i]->setEnabled(false);
                break;
            case 15:
                pDynamique.labelB[num_vue][num_badge_i]->setEnabled(false);
                break;
            } //fin switch

//qDebug() << "[4] avant affichage";
            //affichage position exacte badge
            if (num_vue==1 && num_pers==1)  //taille petite, pas de décalement
                pDynamique.labelB[num_vue][num_badge_i]->setGeometry(tll->ptBadge[num_vue].x, tll->ptBadge[num_vue].y,20,20);
            else if (num_vue==1 && num_pers!=1) //taile petite, décalement
                pDynamique.labelB[num_vue][num_badge_i]->setGeometry(tll->ptBadge[num_vue].x + (10*num_pers), tll->ptBadge[num_vue].y,20,20);

            else if (num_vue!=1 && num_pers==1) //taille grande, pas de décalement
                pDynamique.labelB[num_vue][num_badge_i]->setGeometry(tll->ptBadge[num_vue].x, tll->ptBadge[num_vue].y,30,20);
            else    //taille grande, décalement
                pDynamique.labelB[num_vue][num_badge_i]->setGeometry(tll->ptBadge[num_vue].x + (20*num_pers), tll->ptBadge[num_vue].y,30,20);

            //affichage identité personne
            if (num_pers != -1) {
               pDynamique.labelB[num_vue][num_badge_i]->setToolTip("<img src=':" + tll->photo[num_pers] + "'/>"
                                                             +" Badge "+ QString::number(num_badge_i) +" de : "
                                                             + tll->nom[num_pers] +" "  + tll->prenom[num_pers]
                                                             +QString::fromUtf8(" Société : ")+ tll->societe[num_pers]);

            } else { //badge pas affecté
                pDynamique.labelB[num_vue][num_badge_i]->setToolTip(QString::fromUtf8("Badge non affecté à une personne"));
            }

        } //fin for
    } //fin if

    pBdd->setBadgeActif(num_badge_i);      //le badge n'est pas perdu
    return true;

}
Esempio n. 13
0
//---------------------------------------------------------------------------
//  setWordVariation
//
//! Display the front and back hooks of a word.
//
//! @param word the word whose hooks are displayed
//! @param variation the variation of the word to display
//---------------------------------------------------------------------------
void
WordVariationDialog::setWordVariation(const QString& word, WordVariationType
                                      variation)
{
    bool forceAlphabetSort = false;
    bool origGroupByAnagrams = MainSettings::getWordListGroupByAnagrams();
    QString title, topTitle, middleTitle, bottomTitle;
    SearchSpec spec;
    SearchCondition condition;
    QList<SearchSpec> topSpecs;
    QList<SearchSpec> middleSpecs;
    QList<SearchSpec> bottomSpecs;
    switch (variation) {

        case VariationAnagrams:
        title = "Anagrams for: " + word;
        condition.type = SearchCondition::AnagramMatch;
        condition.stringValue = word;
        spec.conditions.append(condition);
        topSpecs.append(spec);
        topTitle = "Anagrams";
        break;

        case VariationSubanagrams:
        title = "Subanagrams for: " + word;
        condition.type = SearchCondition::SubanagramMatch;
        condition.stringValue = word;
        spec.conditions.append(condition);
        topSpecs.append(spec);
        topTitle = "Subanagrams";
        forceAlphabetSort = true;
        break;

        case VariationHooks:
        title = "Hooks for: " + word;
        condition.type = SearchCondition::PatternMatch;
        condition.stringValue = "?" + word;
        spec.conditions.append(condition);
        topSpecs.append(spec);
        condition.stringValue = word + "?";
        spec.conditions.clear();
        spec.conditions.append(condition);
        middleSpecs.append(spec);
        topTitle = "Front Hooks";
        middleTitle = "Back Hooks";
        forceAlphabetSort = true;
        break;

        case VariationAnagramHooks:
        title = "Anagram Hooks for: " + word;
        condition.type = SearchCondition::AnagramMatch;
        condition.stringValue = "?" + word;
        spec.conditions.append(condition);
        topSpecs.append(spec);
        topTitle = "Anagram Hooks";
        break;

        case VariationBlankAnagrams:
        title = "Blank Anagrams for: " + word;
        condition.type = SearchCondition::AnagramMatch;
        for (int i = 0; i < int(word.length()); ++i) {
            condition.stringValue = word.left(i) + "?" +
                word.right(word.length() - i - 1);
            spec.conditions.clear();
            spec.conditions.append(condition);
            topSpecs.append(spec);
        }
        topTitle = "Blank Anagrams";
        break;

        case VariationBlankMatches:
        title = "Blank Matches for: " + word;
        condition.type = SearchCondition::PatternMatch;
        for (int i = 0; i < int(word.length()); ++i) {
            condition.stringValue = word.left(i) + "?" +
                word.right(word.length() - i - 1);
            spec.conditions.clear();
            spec.conditions.append(condition);
            topSpecs.append(spec);
        }
        topTitle = "Blank Matches";
        forceAlphabetSort = true;
        break;

        case VariationExtensions:
        title = "Extensions for: " + word;
        condition.type = SearchCondition::PatternMatch;
        condition.stringValue = "*?" + word;
        spec.conditions.append(condition);
        topSpecs.append(spec);
        condition.stringValue = word + "?*";
        spec.conditions.clear();
        spec.conditions.append(condition);
        middleSpecs.append(spec);
        condition.stringValue = "*?" + word + "?*";
        spec.conditions.clear();
        spec.conditions.append(condition);
        bottomSpecs.append(spec);
        topTitle = "Front Extensions";
        middleTitle = "Back Extensions";
        bottomTitle = "Double Extensions";
        forceAlphabetSort = true;
        break;

        case VariationTranspositions:
        title = "Transpositions for: " + word;
        condition.type = SearchCondition::PatternMatch;
        for (int i = 0; i < int(word.length()); ++i) {
            condition.stringValue = word.left(i) + word.mid(i + 1, 1) +
                word.mid(i, 1) + word.right(word.length() - i - 2);
            spec.conditions.clear();
            spec.conditions.append(condition);
            topSpecs.append(spec);
        }
        topTitle = "Transpositions";
        break;

        default: break;
    }

    if (!wordEngine->isAcceptable(lexicon, word))
        title += "*";
    setWindowTitle(title);
    wordLabel->setText(title);

    QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));

    // Populate the top list
    QList<WordTableModel::WordItem> wordItems = getWordItems(topSpecs);

    // FIXME: Probably not the right way to get alphabetical sorting instead
    // of alphagram sorting
    if (forceAlphabetSort)
        MainSettings::setWordListGroupByAnagrams(false);
    topModel->addWords(wordItems);
    if (forceAlphabetSort)
        MainSettings::setWordListGroupByAnagrams(origGroupByAnagrams);

    int topWords = topModel->rowCount();
    topTitle += " : " + QString::number(topWords) + " word";
    if (topWords != 1)
        topTitle += "s";
    topLabel->setText(topTitle);

    // Populate the middle list
    if (!middleSpecs.empty()) {
        wordItems = getWordItems(middleSpecs);

        // FIXME: Probably not the right way to get alphabetical sorting
        // instead of alphagram sorting
        if (forceAlphabetSort)
            MainSettings::setWordListGroupByAnagrams(false);
        middleModel->addWords(wordItems);
        if (forceAlphabetSort)
            MainSettings::setWordListGroupByAnagrams(origGroupByAnagrams);

        int middleWords = middleModel->rowCount();
        middleTitle += " : " + QString::number(middleWords) + " word";
        if (middleWords != 1)
            middleTitle += "s";
        middleLabel->setText(middleTitle);
    }

    // Populate the bottom list
    if (!bottomSpecs.empty()) {
        wordItems = getWordItems(bottomSpecs);

        // FIXME: Probably not the right way to get alphabetical sorting
        // instead of alphagram sorting
        if (forceAlphabetSort)
            MainSettings::setWordListGroupByAnagrams(false);
        bottomModel->addWords(wordItems);
        if (forceAlphabetSort)
            MainSettings::setWordListGroupByAnagrams(origGroupByAnagrams);

        int bottomWords = bottomModel->rowCount();
        bottomTitle += " : " + QString::number(bottomWords) + " word";
        if (bottomWords != 1)
            bottomTitle += "s";
        bottomLabel->setText(bottomTitle);
    }

    QApplication::restoreOverrideCursor();
}
Esempio n. 14
0
WalletModel::SendCoinsReturn WalletModel::sendCoins(const QList<SendCoinsRecipient> &recipients)
{
    qint64 total = 0;
    QSet<QString> setAddress;
    QString hex;

    if(recipients.empty())
    {
        return OK;
    }

    // Pre-check input data for validity
    foreach(const SendCoinsRecipient &rcp, recipients)
    {
        if(!validateAddress(rcp.address))
        {
            return InvalidAddress;
        }
        setAddress.insert(rcp.address);

        if(rcp.amount <= 0)
        {
            return InvalidAmount;
        }
        total += rcp.amount;
    }

    if(recipients.size() > setAddress.size())
    {
        return DuplicateAddress;
    }

    if(total > getBalance())
    {
        return AmountExceedsBalance;
    }

    if((total + nTransactionFee) > getBalance())
    {
        return SendCoinsReturn(AmountWithFeeExceedsBalance, nTransactionFee);
    }

    {
        LOCK2(cs_main, wallet->cs_wallet);

        // Sendmany
        std::vector<std::pair<CScript, int64> > vecSend;
        foreach(const SendCoinsRecipient &rcp, recipients)
        {
            CScript scriptPubKey;
            scriptPubKey.SetDestination(CBitcoinAddress(rcp.address.toStdString()).Get());
            vecSend.push_back(make_pair(scriptPubKey, rcp.amount));
        }

        CWalletTx wtx;
        CReserveKey keyChange(wallet);
        int64 nFeeRequired = 0;
        std::string strFailReason;
        bool fCreated = wallet->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired, strFailReason);

        if(!fCreated)
        {
            if((total + nFeeRequired) > wallet->GetBalance())
            {
                return SendCoinsReturn(AmountWithFeeExceedsBalance, nFeeRequired);
            }
            emit message(tr("Send Coins"), QString::fromStdString(strFailReason),
                         CClientUIInterface::MSG_ERROR);
            return TransactionCreationFailed;
        }
        if(!uiInterface.ThreadSafeAskFee(nFeeRequired))
        {
            return Aborted;
        }
        if(!wallet->CommitTransaction(wtx, keyChange))
        {
            return TransactionCommitFailed;
        }
        hex = QString::fromStdString(wtx.GetHash().GetHex());
    }
Esempio n. 15
0
WalletModel::SendCoinsReturn WalletModel::prepareTransaction(WalletModelTransaction &transaction, const CCoinControl *coinControl)
{
    CAmount total = 0;
    bool fSubtractFeeFromAmount = false;
    QList<SendCoinsRecipient> recipients = transaction.getRecipients();
    std::vector<CRecipient> vecSend;

    if(recipients.empty())
    {
        return OK;
    }

    // This should never really happen, yet another safety check, just in case.
    if(wallet->IsLocked()) {
        return TransactionCreationFailed;
    }

    QSet<QString> setAddress; // Used to detect duplicates
    int nAddresses = 0;

    // Pre-check input data for validity
    Q_FOREACH(const SendCoinsRecipient &rcp, recipients)
    {
        if (rcp.fSubtractFeeFromAmount)
            fSubtractFeeFromAmount = true;

        if (rcp.paymentRequest.IsInitialized())
        {   // PaymentRequest...
            CAmount subtotal = 0;
            const payments::PaymentDetails& details = rcp.paymentRequest.getDetails();
            for (int i = 0; i < details.outputs_size(); i++)
            {
                const payments::Output& out = details.outputs(i);
                if (out.amount() <= 0) continue;
                subtotal += out.amount();
                const unsigned char* scriptStr = (const unsigned char*)out.script().data();
                CScript scriptPubKey(scriptStr, scriptStr+out.script().size());
                CAmount nAmount = out.amount();
                CRecipient recipient = {scriptPubKey, nAmount, rcp.fSubtractFeeFromAmount};
                vecSend.push_back(recipient);
            }
            if (subtotal <= 0)
            {
                return InvalidAmount;
            }
            total += subtotal;
        }
        else
        {   // User-entered dash address / amount:
            if(!validateAddress(rcp.address))
            {
                return InvalidAddress;
            }
            if(rcp.amount <= 0)
            {
                return InvalidAmount;
            }
            setAddress.insert(rcp.address);
            ++nAddresses;

            CScript scriptPubKey = GetScriptForDestination(CBitcoinAddress(rcp.address.toStdString()).Get());
            CRecipient recipient = {scriptPubKey, rcp.amount, rcp.fSubtractFeeFromAmount};
            vecSend.push_back(recipient);

            total += rcp.amount;
        }
    }
    if(setAddress.size() != nAddresses)
    {
        return DuplicateAddress;
    }

    CAmount nBalance = getBalance(coinControl);

    if(total > nBalance)
    {
        return AmountExceedsBalance;
    }

    {
        LOCK2(cs_main, wallet->cs_wallet);

        transaction.newPossibleKeyChange(wallet);

        CAmount nFeeRequired = 0;
        int nChangePosRet = -1;
        std::string strFailReason;

        CWalletTx *newTx = transaction.getTransaction();
        CReserveKey *keyChange = transaction.getPossibleKeyChange();

        if(recipients[0].fUseInstantSend && total > sporkManager.GetSporkValue(SPORK_5_INSTANTSEND_MAX_VALUE)*COIN){
            Q_EMIT message(tr("Send Coins"), tr("InstantSend doesn't support sending values that high yet. Transactions are currently limited to %1 DASH.").arg(sporkManager.GetSporkValue(SPORK_5_INSTANTSEND_MAX_VALUE)),
                         CClientUIInterface::MSG_ERROR);
            return TransactionCreationFailed;
        }

        bool fCreated = wallet->CreateTransaction(vecSend, *newTx, *keyChange, nFeeRequired, nChangePosRet, strFailReason, coinControl, true, recipients[0].inputType, recipients[0].fUseInstantSend);
        transaction.setTransactionFee(nFeeRequired);
        if (fSubtractFeeFromAmount && fCreated)
            transaction.reassignAmounts(nChangePosRet);

        if(recipients[0].fUseInstantSend) {
            if(newTx->tx->GetValueOut() > sporkManager.GetSporkValue(SPORK_5_INSTANTSEND_MAX_VALUE)*COIN) {
                Q_EMIT message(tr("Send Coins"), tr("InstantSend doesn't support sending values that high yet. Transactions are currently limited to %1 DASH.").arg(sporkManager.GetSporkValue(SPORK_5_INSTANTSEND_MAX_VALUE)),
                             CClientUIInterface::MSG_ERROR);
                return TransactionCreationFailed;
            }
            if(newTx->tx->vin.size() > CTxLockRequest::WARN_MANY_INPUTS) {
                Q_EMIT message(tr("Send Coins"), tr("Used way too many inputs (>%1) for this InstantSend transaction, fees could be huge.").arg(CTxLockRequest::WARN_MANY_INPUTS),
                             CClientUIInterface::MSG_WARNING);
            }
        }

        if(!fCreated)
        {
            if(!fSubtractFeeFromAmount && (total + nFeeRequired) > nBalance)
            {
                return SendCoinsReturn(AmountWithFeeExceedsBalance);
            }
            Q_EMIT message(tr("Send Coins"), QString::fromStdString(strFailReason),
                         CClientUIInterface::MSG_ERROR);
            return TransactionCreationFailed;
        }

        // reject absurdly high fee. (This can never happen because the
        // wallet caps the fee at maxTxFee. This merely serves as a
        // belt-and-suspenders check)
        if (nFeeRequired > maxTxFee)
            return AbsurdFee;
    }

    return SendCoinsReturn(OK);
}
Esempio n. 16
0
std::vector<TripleField> isocolorCells(const TripleField& t, const std::vector<double>& colorLevels)
{
	QList<Triple> intersections;
	unsigned int colorCount = colorLevels.size(), size = t.size();
	for (unsigned int k = 0; k < colorCount; k++){
		double val = colorLevels[k];
		for (unsigned int i = 0; i < size; i++){
			int ii = (i + 1)%size;
			Triple ti = t[i], tii = t[ii];
			double zi = ti.z, zii = tii.z;

			if (val == zi){
				if (!intersections.contains(ti))
					intersections.push_back(ti);
				continue;
			} else if (val == zii){
				if (!intersections.contains(tii))
					intersections.push_back(tii);
				continue;
			}

			bool outer = (val > zii && val < zi);
			bool inner = (val > zi && val < zii);
			if (inner || outer){
				Triple d = tii - ti;
				double f = (val - zi)/d(2);
				double component[3];
				for (unsigned int j = 0; j < 3; j++)
					component[j] = ti(j) + f*d(j);

				intersections.push_back(Triple(component[0], component[1], val));
			}
		}
	}

	std::vector<TripleField> cells;
	if (intersections.empty())
		return cells;

	Triple p = intersections[0], pp = intersections[1];
	TripleField firstCell, lastCell;
	firstCell.push_back(p);
	firstCell.push_back(pp);

	double level = p.z;
	for (unsigned int j = 0; j < size; j++){
		Triple tj = t[j];
		if (tj.z < level)
			firstCell.push_back(tj);
	}
	cells.push_back(firstCell);

	unsigned int intPairs = intersections.size()/2;
	for (unsigned int i = 1; i < intPairs; i++){
		TripleField cell;
		cell.push_back(p);
		cell.push_back(pp);

		double prevLevel = p.z;
		unsigned int k = 2*i;
		p = intersections[k];
		pp = intersections[k + 1];

		level = p.z;
		for (unsigned int j = 0; j < size; j++){
			Triple tj = t[j];
			if (prevLevel < tj.z && tj.z < level)
				cell.push_back(tj);
		}

		cell.push_back(p);
		cell.push_back(pp);
		cells.push_back(cell);
	}

	lastCell.push_back(p);
	lastCell.push_back(pp);
	for (unsigned int j = 0; j < size; j++){
		Triple tj = t[j];
		if (tj.z > level)
			lastCell.push_back(tj);
	}
	cells.push_back(lastCell);
	return cells;
}
Esempio n. 17
0
void Worker::run() {
	while (1) {
		res->requestSemaphore.acquire(1);
		if (die) {
			break;
		}

		// get next page to render
		res->requestMutex.lock();
		int page, width, index;
		map<int,pair<int,int> >::iterator less = res->requests.lower_bound(res->center_page);
		map<int,pair<int,int> >::iterator greater = less--;

		if (greater != res->requests.end()) {
			if (greater != res->requests.begin()) {
				// favour nearby page, go down first
				if (greater->first + less->first <= res->center_page * 2) {
					page = greater->first;
					index = greater->second.first;
					width = greater->second.second;
					res->requests.erase(greater);
				} else {
					page = less->first;
					index = less->second.first;
					width = less->second.second;
					res->requests.erase(less);
				}
			} else {
				page = greater->first;
				index = greater->second.first;
				width = greater->second.second;
				res->requests.erase(greater);
			}
		} else {
			page = less->first;
			index = less->second.first;
			width = less->second.second;
			res->requests.erase(less);
		}
		res->requestMutex.unlock();

		// check for duplicate requests
		res->k_page[page].mutex.lock();
		if (res->k_page[page].status[index] == width &&
				res->k_page[page].rotation[index] == res->rotation) {
			res->k_page[page].mutex.unlock();
			continue;
		}
		int rotation = res->rotation;
		res->k_page[page].mutex.unlock();

		// open page
#ifdef DEBUG
		cerr << "    rendering page " << page << " for index " << index << endl;
#endif
		Poppler::Page *p = res->doc->page(page);
		if (p == NULL) {
			cerr << "failed to load page " << page << endl;
			continue;
		}

		// render page
		float dpi = 72.0 * width / res->get_page_width(page);
		QImage img = p->renderToImage(dpi, dpi, -1, -1, -1, -1,
				static_cast<Poppler::Page::Rotation>(rotation));

		if (img.isNull()) {
			cerr << "failed to render page " << page << endl;
			continue;
		}

		// invert to current color setting
		if (res->inverted_colors) {
			img.invertPixels();
		}

		// put page
		res->k_page[page].mutex.lock();
		if (!res->k_page[page].img[index].isNull()) {
			res->k_page[page].img[index] = QImage(); // assign null image
		}

		// adjust all available images to current color setting
		if (res->k_page[page].inverted_colors != res->inverted_colors) {
			res->k_page[page].inverted_colors = res->inverted_colors;
			for (int i = 0; i < 3; i++) {
				res->k_page[page].img[i].invertPixels();
			}
			res->k_page[page].thumbnail.invertPixels();
		}
		res->k_page[page].img[index] = img;
		res->k_page[page].status[index] = width;
		res->k_page[page].rotation[index] = rotation;
		res->k_page[page].mutex.unlock();

		res->garbageMutex.lock();
		res->garbage.insert(page); // TODO add index information?
		res->garbageMutex.unlock();

		emit page_rendered(page);

		// collect goto links
		res->link_mutex.lock();
		if (res->k_page[page].links == NULL) {
			res->link_mutex.unlock();

			QList<Poppler::Link *> *links = new QList<Poppler::Link *>;
			QList<Poppler::Link *> l = p->links();
			links->swap(l);

			res->link_mutex.lock();
			res->k_page[page].links = links;
		}
		if (res->k_page[page].text == NULL) {
			res->link_mutex.unlock();

			QList<Poppler::TextBox *> text = p->textList();
			// assign boxes to lines
			// make single parts from chained boxes
			set<Poppler::TextBox *> used;
			QList<SelectionPart *> selection_parts;
			Q_FOREACH(Poppler::TextBox *box, text) {
				if (used.find(box) != used.end()) {
					continue;
				}
				used.insert(box);

				SelectionPart *p = new SelectionPart(box);
				selection_parts.push_back(p);
				Poppler::TextBox *next = box->nextWord();
				while (next != NULL) {
					used.insert(next);
					p->add_word(next);
					next = next->nextWord();
				}
			}

			// sort by y coordinate
			qStableSort(selection_parts.begin(), selection_parts.end(), selection_less_y);

			QRectF line_box;
			QList<SelectionLine *> *lines = new QList<SelectionLine *>();
			Q_FOREACH(SelectionPart *part, selection_parts) {
				QRectF box = part->get_bbox();
				// box fits into line_box's line
				if (!lines->empty() && box.y() <= line_box.center().y() && box.bottom() > line_box.center().y()) {
					float ratio_w = box.width() / line_box.width();
					float ratio_h = box.height() / line_box.height();
					if (ratio_w < 1.0f) {
						ratio_w = 1.0f / ratio_w;
					}
					if (ratio_h < 1.0f) {
						ratio_h = 1.0f / ratio_h;
					}
					if (ratio_w > 1.3f && ratio_h > 1.3f) {
						lines->back()->sort();
						lines->push_back(new SelectionLine(part));
						line_box = part->get_bbox();
					} else {
						lines->back()->add_part(part);
					}
				// it doesn't fit, create new line
				} else {
					if (!lines->empty()) {
						lines->back()->sort();
					}
					lines->push_back(new SelectionLine(part));
					line_box = part->get_bbox();
				}
			}
			if (!lines->empty()) {
				lines->back()->sort();
			}

			res->link_mutex.lock();
			res->k_page[page].text = lines;
		}
Esempio n. 18
0
/**
  This upload the results from texture image to the graphics card
  */
void cwImageTexture::updateData() {
    if(!isDirty()) { return; }

    if(DeleteTexture) {
        deleteGLTexture();
        TextureDirty = false;
        return;
    }

    if(TextureUploadTask == nullptr) {
        TextureDirty = false;
        return;
    }

    if(TextureUploadTask->isRunning()) { return; }

    QList<QPair<QByteArray, QSize> > mipmaps = TextureUploadTask->mipmaps();
    ScaleTexCoords = TextureUploadTask->scaleTexCoords();

    if(mipmaps.empty()) { return; }

    QSize firstLevel = mipmaps.first().second;
    if(!cwTextureUploadTask::isDivisibleBy4(firstLevel)) {
        qDebug() << "Trying to upload an image that isn't divisible by 4. This will crash ANGLE on windows." << LOCATION;
        TextureDirty = false;
        return;
    }

    //Load the data into opengl
    bind();

    //Get the max texture size
    GLint maxTextureSize;
    glGetIntegerv(GL_MAX_TEXTURE_SIZE, &maxTextureSize);

    int trueMipmapLevel = 0;
    for(int mipmapLevel = 0; mipmapLevel < mipmaps.size(); mipmapLevel++) {

        //Get the mipmap data
        QPair<QByteArray, QSize> image = mipmaps.at(mipmapLevel);
        QByteArray imageData = image.first;
        QSize size = image.second;

        if(size.width() < maxTextureSize && size.height() < maxTextureSize) {
            glCompressedTexImage2D(GL_TEXTURE_2D, trueMipmapLevel, GL_COMPRESSED_RGB_S3TC_DXT1_EXT,
                                   size.width(), size.height(), 0,
                                   imageData.size(), imageData.data());

            trueMipmapLevel++;

#ifdef Q_OS_WIN
            //Only upload one texture, because some intel cards, don't support npot dxt1 copression, so we just used nearest
            //FIXME: ADD to rendering settings!
            break;
#endif //Q_OS_WIN
        }
    }

    release();

    deleteLoadNoteTask();

    TextureDirty = false;
}
void QmitkMatchPointRegistrationEvaluator::CheckInputs()
{
  if (!m_activeEvaluation)
  {
  QList<mitk::DataNode::Pointer> dataNodes = this->GetDataManagerSelection();
  this->m_autoMoving = false;
  this->m_autoTarget = false;
  this->m_spSelectedMovingNode = NULL;
  this->m_spSelectedTargetNode = NULL;
  this->m_spSelectedRegNode = NULL;

  if (dataNodes.size() > 0)
  {
    //test if auto select works
    if (mitk::MITKRegistrationHelper::IsRegNode(dataNodes[0]) && dataNodes[0]->GetData())
    {
      this->m_spSelectedRegNode = dataNodes[0];
      dataNodes.pop_front();

      mitk::BaseProperty* uidProp = m_spSelectedRegNode->GetData()->GetProperty(mitk::Prop_RegAlgMovingData);

      if (uidProp)
      {
        //search for the moving node
        mitk::NodePredicateDataProperty::Pointer predicate = mitk::NodePredicateDataProperty::New(mitk::Prop_UID,
          uidProp);
        this->m_spSelectedMovingNode = this->GetDataStorage()->GetNode(predicate);
        this->m_autoMoving = this->m_spSelectedMovingNode.IsNotNull();
      }

      uidProp = m_spSelectedRegNode->GetData()->GetProperty(mitk::Prop_RegAlgTargetData);

      if (uidProp)
      {
        //search for the target node
        mitk::NodePredicateDataProperty::Pointer predicate = mitk::NodePredicateDataProperty::New(mitk::Prop_UID,
          uidProp);
        this->m_spSelectedTargetNode = this->GetDataStorage()->GetNode(predicate);
        this->m_autoTarget = this->m_spSelectedTargetNode.IsNotNull();
      }
    }

    //if still nodes are selected -> ignore possible auto select
    if (!dataNodes.empty())
    {
      mitk::Image* inputImage = dynamic_cast<mitk::Image*>(dataNodes[0]->GetData());

      if (inputImage)
      {
        this->m_spSelectedMovingNode = dataNodes[0];
        this->m_autoMoving = false;
        dataNodes.pop_front();
      }
    }

    if (!dataNodes.empty())
    {
      mitk::Image* inputImage = dynamic_cast<mitk::Image*>(dataNodes[0]->GetData());

      if (inputImage)
      {
        this->m_spSelectedTargetNode = dataNodes[0];
        this->m_autoTarget = false;
        dataNodes.pop_front();
      }
    }
  }
  }
}
Esempio n. 20
0
void TablePrintDialog::paintPage(int pagenum)
{
  //Delete all
  QList<QGraphicsItem*> L = pageScene.items();
  while ( ! L.empty() )
  {
    pageScene.removeItem( L.first() );
    delete L.first();
    L.removeFirst();
  }

  //Table header
  int csize=0;
  for (int i=0; i<model->columnCount(); i++)
  {
    int logicalIndex=tableView->horizontalHeader()->logicalIndex(i);
    QString txt = model->headerData(logicalIndex,Qt::Horizontal,Qt::DisplayRole).toString();
    QGraphicsTextItem *item=new QGraphicsTextItem();
    item->setFont(headerFont);
    txt=headerFmt->elidedText(txt,Qt::ElideRight,QVariant(colSizes[logicalIndex].rawValue()).toInt()-8);
    item->setPlainText(txt);
    //item->moveBy((csize*columnMultiplier)+leftMargin,topMargin+headerSize+(spacing*2));
    item->moveBy(csize+leftMargin,topMargin+headerSize+(spacing*2));
    csize=csize+QVariant(colSizes[logicalIndex].rawValue()).toInt();
    pageScene.addItem(item);
  }

  //Table rows
  qreal dx,dy;
  QPen pen(Qt::gray, 1);
  QBrush brush(Qt::gray,Qt::SolidPattern);
  int borderAdjust=rowHeight / 5;

  for (int i=0; i<lines; i++)
  {
    csize=0;
    dy=(i*rowHeight)+topMargin+headerSize+(rowHeight*2);
    int modelIdxY=(pagenum-1)*lines+i;
    if (modelIdxY>=model->rowCount())
    {
      break;
    }

    for (int j=0; j<model->columnCount(); j++)
    {
      int logicalIndex=tableView->horizontalHeader()->logicalIndex(j);
      int actColSize=QVariant(colSizes[logicalIndex].rawValue()).toInt();
      QString txt = model->data(model->index(modelIdxY,logicalIndex)).toString();
      QGraphicsTextItem *item=new QGraphicsTextItem();
      item->setFont(font);
      txt=fmt->elidedText(txt,Qt::ElideRight,actColSize-8);
      item->setPlainText(txt);
      //qreal dx=(csize*columnMultiplier)+leftMargin;
      dx=csize+leftMargin;
      item->moveBy(dx,dy);

      //rectangle
      if (gridMode==NormalGrid || gridMode==AlternateWithGrid)
      {
        pageScene.addRect(dx,dy+borderAdjust,actColSize,rowHeight);
      }
      pageScene.addItem(item);
      csize=csize+actColSize;
    }

    if (gridMode==AlternateColor || gridMode==AlternateWithGrid)
    {
      int modulo=i % 2;
      if (modulo==0) {
        //rectangle grey
        QGraphicsRectItem *rItem=pageScene.addRect(leftMargin,dy+borderAdjust,csize,rowHeight,pen,brush);
        rItem->setZValue(-1);
      }
    }

  }

  // Page header
  if (headerSize > 0)
  {
    //line
    pageScene.addLine(leftMargin,headerSize+topMargin,pageScene.width()-rightMargin, headerSize+topMargin,QPen(Qt::black, 1.0));

    //tile
    QGraphicsTextItem *titleItem=new QGraphicsTextItem();
    titleItem->setFont(titleFont);
    titleItem->setPlainText(headerText);
    int titleWidth=titleFmt->width(headerText);
    double xpos=(pageScene.width()/2)-(titleWidth/2);
    double ypos=(headerSize/2)-(titleFmt->height()/2);
    titleItem->moveBy(xpos,ypos+topMargin);
    pageScene.addItem(titleItem);

    //std text
    QGraphicsTextItem *item=new QGraphicsTextItem();
    item->setFont(font);
    item->setPlainText(headerStdText);
    item->moveBy(leftMargin,headerSize-rowHeight-spacing+topMargin);
    pageScene.addItem(item);
  }

  // footer
  if (footerSize > 0)
  {
    pageScene.addLine(leftMargin,pageScene.height()-footerSize-bottomMargin,pageScene.width()-rightMargin, pageScene.height()-footerSize-bottomMargin,QPen(Qt::black, 1.0));
    QGraphicsTextItem *item=new QGraphicsTextItem();
    item->setFont(font);
    item->setPlainText(footerText+QString::number(pages)+" / "+QString::number(pagenum));
    item->moveBy(leftMargin,pageScene.height()-footerSize-bottomMargin+spacing);
    pageScene.addItem(item);
  }
  //pageScene.update();
}
Esempio n. 21
0
SettingsDialog::SettingsDialog(
            const QList<QAudioDeviceInfo> &availableInputDevices,
            const QList<QAudioDeviceInfo> &availableOutputDevices,
            QWidget *parent)
    :   QDialog(parent)
    ,   m_windowFunction(DefaultWindowFunction)
    ,   m_inputDeviceComboBox(new QComboBox(this))
    ,   m_outputDeviceComboBox(new QComboBox(this))
    ,   m_windowFunctionComboBox(new QComboBox(this))
{
    QVBoxLayout *dialogLayout = new QVBoxLayout(this);

    // Populate combo boxes

    QAudioDeviceInfo device;
    foreach (device, availableInputDevices)
        m_inputDeviceComboBox->addItem(device.deviceName(),
                                       qVariantFromValue(device));
    foreach (device, availableOutputDevices)
        m_outputDeviceComboBox->addItem(device.deviceName(),
                                       qVariantFromValue(device));

    m_windowFunctionComboBox->addItem(tr("None"), qVariantFromValue(int(NoWindow)));
    m_windowFunctionComboBox->addItem("Hann", qVariantFromValue(int(HannWindow)));
    m_windowFunctionComboBox->setCurrentIndex(m_windowFunction);

    // Initialize default devices
    if (!availableInputDevices.empty())
        m_inputDevice = availableInputDevices.front();
    if (!availableOutputDevices.empty())
        m_outputDevice = availableOutputDevices.front();

    // Add widgets to layout

    QScopedPointer<QHBoxLayout> inputDeviceLayout(new QHBoxLayout);
    QLabel *inputDeviceLabel = new QLabel(tr("Input device"), this);
    inputDeviceLayout->addWidget(inputDeviceLabel);
    inputDeviceLayout->addWidget(m_inputDeviceComboBox);
    dialogLayout->addLayout(inputDeviceLayout.data());
    inputDeviceLayout.take(); // ownership transferred to dialogLayout

    QScopedPointer<QHBoxLayout> outputDeviceLayout(new QHBoxLayout);
    QLabel *outputDeviceLabel = new QLabel(tr("Output device"), this);
    outputDeviceLayout->addWidget(outputDeviceLabel);
    outputDeviceLayout->addWidget(m_outputDeviceComboBox);
    dialogLayout->addLayout(outputDeviceLayout.data());
    outputDeviceLayout.take(); // ownership transferred to dialogLayout

    QScopedPointer<QHBoxLayout> windowFunctionLayout(new QHBoxLayout);
    QLabel *windowFunctionLabel = new QLabel(tr("Window function"), this);
    windowFunctionLayout->addWidget(windowFunctionLabel);
    windowFunctionLayout->addWidget(m_windowFunctionComboBox);
    dialogLayout->addLayout(windowFunctionLayout.data());
    windowFunctionLayout.take(); // ownership transferred to dialogLayout

    // Connect
    CHECKED_CONNECT(m_inputDeviceComboBox, SIGNAL(activated(int)),
                    this, SLOT(inputDeviceChanged(int)));
    CHECKED_CONNECT(m_outputDeviceComboBox, SIGNAL(activated(int)),
                    this, SLOT(outputDeviceChanged(int)));
    CHECKED_CONNECT(m_windowFunctionComboBox, SIGNAL(activated(int)),
                    this, SLOT(windowFunctionChanged(int)));

    // Add standard buttons to layout
    QDialogButtonBox *buttonBox = new QDialogButtonBox(this);
    buttonBox->setStandardButtons(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
    dialogLayout->addWidget(buttonBox);

    // Connect standard buttons
    CHECKED_CONNECT(buttonBox->button(QDialogButtonBox::Ok), SIGNAL(clicked()),
                    this, SLOT(accept()));
    CHECKED_CONNECT(buttonBox->button(QDialogButtonBox::Cancel), SIGNAL(clicked()),
                    this, SLOT(reject()));

    setLayout(dialogLayout);
}
void QgsPointDisplacementRenderer::createDisplacementGroups( QgsVectorLayer* vlayer, const QgsRectangle& viewExtent )
{
  if ( !vlayer || ( vlayer->wkbType() != QGis::WKBPoint && vlayer->wkbType() != QGis::WKBPoint25D ) )
  {
    return;
  }

  mDisplacementGroups.clear();
  mDisplacementIds.clear();

  //use a spatial index to check if there is already a point at a position
  QgsSpatialIndex spatialIndex;

  //attributes
  QgsAttributeList attList;
  QList<QString> attributeStrings = usedAttributes();
  QList<QString>::const_iterator attStringIt = attributeStrings.constBegin();
  for ( ; attStringIt != attributeStrings.constEnd(); ++attStringIt )
  {
    attList.push_back( vlayer->fieldNameIndex( *attStringIt ) );
  }

  QgsFeature f;
  QList<QgsFeatureId> intersectList;

  QgsFeatureIterator fit = vlayer->getFeatures( QgsFeatureRequest().setFilterRect( viewExtent ).setSubsetOfAttributes( attList ) );
  while ( fit.nextFeature( f ) )
  {
    intersectList.clear();

    //check, if there is already a point at that position
    if ( f.geometry() )
    {
      intersectList = spatialIndex.intersects( searchRect( f.geometry()->asPoint() ) );
      if ( intersectList.empty() )
      {
        spatialIndex.insertFeature( f );
      }
      else
      {
        //go through all the displacement group maps and search an entry where the id equals the result of the spatial search
        QgsFeatureId existingEntry = intersectList.at( 0 );
        bool found = false;
        QList< QMap<QgsFeatureId, QgsFeature> >::iterator it = mDisplacementGroups.begin();
        for ( ; it != mDisplacementGroups.end(); ++it )
        {
          if ( it->size() > 0 && it->contains( existingEntry ) )
          {
            found = true;
            QgsFeature feature;
            it->insert( f.id(), f );
            mDisplacementIds.insert( f.id() );
            break;
          }
        }

        if ( !found )//insert the already existing feature and the new one into a map
        {
          QMap<QgsFeatureId, QgsFeature> newMap;
          QgsFeature existingFeature;
          vlayer->getFeatures( QgsFeatureRequest().setFilterFid( existingEntry ) ).nextFeature( existingFeature );
          newMap.insert( existingEntry, existingFeature );
          mDisplacementIds.insert( existingEntry );
          newMap.insert( f.id(), f );
          mDisplacementIds.insert( f.id() );
          mDisplacementGroups.push_back( newMap );
        }
      }
    }
  }
}
Esempio n. 23
0
template<> void
QConsoleWidget::_pf<void, SetToCommand>(
        QConsoleWidget * thisp,QList<QConsoleWidgetCommand> command ) {
    //TODO: ...
    auto tc = thisp->textCursor();
    tc.setPosition( thisp->promptEndPos_);
    tc.movePosition(QTextCursor::End, QTextCursor::KeepAnchor,0);
    thisp->setTextCursor( tc );

    if ( command.empty() ) {
        tc.removeSelectedText();
        thisp->setTextCursor(tc);
		return ;
    }

    auto tryAddReturn = [](const QString & str)->QString {
        if (str.isEmpty()) { return str; }
        if (str.endsWith("\n")) { return str; }
        return (str + "\n");
    };

    if (command.size()==1 ) {
        thisp->insertPlainText(  command.begin()->command );
    }
    else if (command.size() == 2) {
        auto b0 = command.begin();
        auto b1 = b0 + 1;
        if (b1->command.isEmpty()) {
            thisp->insertPlainText(b0->command);
        }
        else {
            thisp->insertPlainText(tryAddReturn(b0->command));
            thisp->insertPlainText(b1->command);
        }
    }
    else {

        auto b = command.begin();
        auto e = command.end() - 2;

        for (;b!=e;++b ) {
            const QString & temp = tryAddReturn( b->command );
            if (temp.isEmpty() == false) {
                thisp->insertPlainText(temp);
            }
        }

        b = e;
        e = e + 1;

        if (e->command.isEmpty()) {
            thisp->insertPlainText(b->command);
        }
        else {
            thisp->insertPlainText(tryAddReturn(b->command));
            thisp->insertPlainText(e->command);
        }

    }

}
Esempio n. 24
0
void WebUI::init()
{
    Preferences* const pref = Preferences::instance();
    Logger* const logger = Logger::instance();

    if (pref->isWebUiEnabled()) {
        const quint16 port = pref->getWebUiPort();
        if (m_port != port) {
            Net::PortForwarder::instance()->deletePort(port);
            m_port = port;
        }

        if (httpServer_) {
            if (httpServer_->serverPort() != m_port)
                httpServer_->close();
        }
        else {
            webapp_ = new WebApplication(this);
            httpServer_ = new Http::Server(webapp_, this);
        }

#ifndef QT_NO_OPENSSL
        if (pref->isWebUiHttpsEnabled()) {
            QList<QSslCertificate> certs = QSslCertificate::fromData(pref->getWebUiHttpsCertificate());
            QSslKey key;
            key = QSslKey(pref->getWebUiHttpsKey(), QSsl::Rsa);
            bool certsIsNull = std::any_of(certs.begin(), certs.end(), [](QSslCertificate c) { return c.isNull(); });
            if (!certsIsNull && !certs.empty() && !key.isNull())
                httpServer_->enableHttps(certs, key);
            else
                httpServer_->disableHttps();
        }
        else {
            httpServer_->disableHttps();
        }
#endif

        if (!httpServer_->isListening()) {
            bool success = httpServer_->listen(QHostAddress::Any, m_port);
            if (success)
                logger->addMessage(tr("The Web UI is listening on port %1").arg(m_port));
            else
                logger->addMessage(tr("Web UI Error - Unable to bind Web UI to port %1").arg(m_port), Log::CRITICAL);
        }

        // DynDNS
        if (pref->isDynDNSEnabled()) {
            if (!dynDNSUpdater_)
                dynDNSUpdater_ = new Net::DNSUpdater(this);
            else
                dynDNSUpdater_->updateCredentials();
        }
        else {
            if (dynDNSUpdater_)
                delete dynDNSUpdater_;
        }

        // Use UPnP/NAT-PMP for Web UI
        if (pref->useUPnPForWebUIPort())
            Net::PortForwarder::instance()->addPort(m_port);
        else
            Net::PortForwarder::instance()->deletePort(m_port);
    }
    else {
        if (httpServer_)
            delete httpServer_;
        if (webapp_)
            delete webapp_;
        if (dynDNSUpdater_)
            delete dynDNSUpdater_;
        Net::PortForwarder::instance()->deletePort(m_port);
    }
}
Esempio n. 25
0
QVariant parseValue(const QDomElement& where)
{
	QDomElement ce = where.firstChildElement();
	QString c = ce.tagName();
	QString contents;
	
	if(c.isNull())
	{
		contents = where.text();
		c = "string";
	}
	else
		contents = ce.firstChild().toText().data();
	
	if(c == "boolean")
		return contents.toInt() != 0;
	else if(c == "i4" || c == "int")
		return contents.toInt();
	else if(c == "double")
		return contents.toDouble();
	else if(c == "string")
		return contents;
	else if(c == "base64")
		return QByteArray::fromBase64(contents.toLatin1());
	else if(c == "dateTime.iso8601")
		return QDateTime::fromString(contents, Qt::ISODate);
	else if(c == "array")
	{
		QDomElement data = ce.firstChildElement("data");
		if(data.isNull())
			return QVariant();
		
		QDomElement v = data.firstChildElement("value");
		QList<QVariant> variantList;
		bool allstring = true;
		
		while(!v.isNull())
		{
			QVariant parsed = parseValue(v);
			variantList << parsed;

			allstring &= parsed.type() == QVariant::String;

			v = v.nextSiblingElement("value");
		}

		if (allstring && !variantList.empty())
		{
			QVariant var(variantList);
			var.convert(QVariant::StringList);
			return var;
		}
		
		return variantList;
	}
	else if(c == "struct")
	{
		QDomElement v = ce.firstChildElement("member");
		QMap<QString, QVariant> variantMap;
		
		while(!v.isNull())
		{
			QDomElement name, value;
			name = v.firstChildElement("name");
			value = v.firstChildElement("value");
			
			if(!name.isNull() && !value.isNull())
			{
				QString n = name.firstChild().toText().data();
				variantMap[n] = parseValue(value);
			}
			else
				qDebug() << "XmlRpc::parseValue(): invalid struct member encountered";
			
			v = v.nextSiblingElement("member");
		}
		
		return variantMap;
	}
	else
	{
		qDebug() << "XmlRpc::parseValue(): Unknown data type:" << c;
		return QVariant();
	}
}
Esempio n. 26
0
static void loadPrivateIdsCallback(GxsIdDetailsType type, const RsIdentityDetails &details, QObject *object, const QVariant &/*data*/)
{
	GxsIdChooser *chooser = dynamic_cast<GxsIdChooser*>(object);
	if (!chooser) {
		return;
	}
    

    // this prevents the objects that depend on what's in the combo-box to activate and
    // perform any change.Only user-changes should cause this.
    chooser->blockSignals(true) ;

	QString text = GxsIdDetails::getNameForType(type, details);
	QString id = QString::fromStdString(details.mId.toStdString());

	/* Find and replace text of exisiting item */
	int index = chooser->findData(id);
	if (index >= 0) {
		chooser->setItemText(index, text);
	} else {
		/* Add new item */
		chooser->addItem(text, id);
		index = chooser->count() - 1;
	}

	QList<QIcon> icons;

	switch (type) {
	case GXS_ID_DETAILS_TYPE_EMPTY:
	case GXS_ID_DETAILS_TYPE_FAILED:
		break;

	case GXS_ID_DETAILS_TYPE_LOADING:
		icons.push_back(GxsIdDetails::getLoadingIcon(details.mId));
		break;

	case GXS_ID_DETAILS_TYPE_DONE:
		GxsIdDetails::getIcons(details, icons);
		break;
        
	case GXS_ID_DETAILS_TYPE_BANNED:
		icons.push_back(QIcon(BANNED_ICON)) ;
		break;
	}

	chooser->setItemData(index, QString("%1_%2").arg((type == GXS_ID_DETAILS_TYPE_DONE) ? TYPE_FOUND_ID : TYPE_UNKNOWN_ID).arg(text), ROLE_SORT);
	chooser->setItemData(index, (type == GXS_ID_DETAILS_TYPE_DONE) ? TYPE_FOUND_ID : TYPE_UNKNOWN_ID, ROLE_TYPE);
	chooser->setItemIcon(index, icons.empty() ? QIcon() : icons[0]);

    	//std::cerr << "ID=" << details.mId << ", chooser->flags()=" << chooser->flags() << ", flags=" << details.mFlags ;
        
    	if((chooser->flags() & IDCHOOSER_NON_ANONYMOUS) && !(details.mFlags & RS_IDENTITY_FLAGS_PGP_LINKED))
        {
            //std::cerr << " - disabling ID - entry = " << index << std::endl;
            chooser->setEntryEnabled(index,false) ;
        }
        
        if(!chooser->isInConstraintSet(details.mId))
            chooser->setEntryEnabled(index,false) ;
        
    chooser->model()->sort(0);

    chooser->blockSignals(false) ;
}
Esempio n. 27
0
void ContinuousPanel::paint(const QRect&, QPainter& painter)
      {
      qreal _offsetPanel = 0;
      qreal _y = 0;
      qreal _oldWidth = 0;        // The last final panel width
      qreal _newWidth = 0;        // New panel width
      qreal _height = 0;
      qreal _leftMarginTotal = 0; // Sum of all elements left margin
      qreal _panelRightPadding = 5;  // Extra space for the panel after last element

      Measure* measure = _score->firstMeasure();

      if (!_active || !measure) {
            _visible = false;
            return;
            }

      if (measure->mmRest()) {
            measure = measure->mmRest();
            }

      System* system   = measure->system();
      if (system == 0) {
            _visible = false;
            return;
            }

      Segment* s      = measure->first();
      double _spatium = _score->spatium();
      if (_width <= 0)
            _width  = s->x();

      //
      // Set panel height for whole system
      //
      _height = 6 * _spatium;
      _y = system->staffYpage(0) + system->page()->pos().y();
      double y2 = 0.0;
      for (int i = 0; i < _score->nstaves(); ++i) {
            SysStaff* ss = system->staff(i);
            if (!ss->show() || !_score->staff(i)->show())
                  continue;
            y2 = ss->y() + ss->bbox().height();
            }
      _height += y2 + 6*_spatium;
      _y -= 6 * _spatium;

      //
      // Check elements at current panel position
      //
      _offsetPanel = -(_sv->xoffset()) / _sv->mag();
      _rect        = QRect(_offsetPanel + _width, _y, 1, _height);
      Page* page   = _score->pages().front();
      QList<Element*> el = page->items(_rect);
      if (el.empty()) {
            _visible = false;
            return;
            }
      qStableSort(el.begin(), el.end(), elementLessThan);

      const Measure*_currentMeasure = 0;
      for (const Element* e : el) {
            e->itemDiscovered = 0;
            if (!e->visible() && !_score->showInvisible())
                  continue;

            if (e->isMeasure()) {
                  _currentMeasure = toMeasure(e);
                  break;
                  }
            }
      if (!_currentMeasure)
            return;

      // Don't show panel if staff names are visible
      if (_currentMeasure == _score->firstMeasure() && _sv->toPhysical(_currentMeasure->canvasPos()).x() > 0) {
            _visible = false;
            return;
            }

      qreal _xPosMeasure       = _currentMeasure->canvasX();
      qreal _measureWidth      = _currentMeasure->width();
      int tick                 = _currentMeasure->tick();
      Fraction _currentTimeSig = _currentMeasure->timesig();
      //qDebug() << "_sv->xoffset()=" <<_sv->xoffset() << " _sv->mag()="<< _sv->mag() <<" s->x=" << s->x() << " width=" << _width << " currentMeasure=" << _currentMeasure->x() << " _xPosMeasure=" << _xPosMeasure;

      //---------------------------------------------------------
      //   findElementWidths
      //      determines the max width for each element types
      //---------------------------------------------------------

      // The first pass serves to get the maximum width for each elements

      qreal lineWidthName = 0;
      qreal _widthClef    = 0;
      qreal _widthKeySig  = 0;
      qreal _widthTimeSig = 0;
      qreal _xPosTimeSig  = 0;

      for (const Element* e : el) {
            e->itemDiscovered = 0;
            if (!e->visible() && !_score->showInvisible())
                  continue;

            if (e->isRest() && toRest(e)->isGap())
                  continue;

            if (e->isStaffLines()) {
                  Staff* currentStaff = _score->staff(e->staffIdx());
                  Segment* parent = _score->tick2segment(tick);

                  // Find maximum width for the staff name
                  QList<StaffName>& staffNamesLong = currentStaff->part()->instrument()->longNames();
                  QString staffName = staffNamesLong.isEmpty() ? " " : staffNamesLong[0].name();
                  if (staffName == "") {
                        QList<StaffName>& staffNamesShort = currentStaff->part()->instrument()->shortNames();
                        staffName = staffNamesShort.isEmpty() ? "" : staffNamesShort[0].name();
                        }
                  Text* newName = new Text(_score);
                  newName->setXmlText(staffName);
                  newName->setParent(parent);
                  newName->setTrack(e->track());
                  newName->setFamily("FreeSans");
                  newName->setSizeIsSpatiumDependent(true);
                  newName->layout();
                  newName->setPlainText(newName->plainText());
                  newName->layout();

                  // Find maximum width for the current Clef
                  Clef* newClef = new Clef(_score);
                  ClefType currentClef = currentStaff->clef(tick);
                  newClef->setClefType(currentClef);
                  newClef->setParent(parent);
                  newClef->setTrack(e->track());
                  newClef->layout();
                  if (newClef->width() > _widthClef)
                        _widthClef = newClef->width();

                  // Find maximum width for the current KeySignature
                  KeySig* newKs = new KeySig(_score);
                  KeySigEvent currentKeySigEvent = currentStaff->keySigEvent(tick);
                  newKs->setKeySigEvent(currentKeySigEvent);
                  // The Parent and the Track must be set to have the key signature layout adjusted to different clefs
                  // This also adds naturals to the key signature (if set in the score style)
                  newKs->setParent(parent);
                  newKs->setTrack(e->track());
                  newKs->setHideNaturals(true);
                  newKs->layout();
                  if (newKs->width() > _widthKeySig)
                        _widthKeySig = newKs->width();

                  // Find maximum width for the current TimeSignature
                  TimeSig* newTs = new TimeSig(_score);

                  // Try to get local time signature, if not, get the current measure one
                  TimeSig* currentTimeSig = currentStaff->timeSig(tick);
                  if (currentTimeSig)
                        newTs->setFrom(currentTimeSig);
                  else
                        newTs->setSig(Fraction(_currentTimeSig.numerator(), _currentTimeSig.denominator()), TimeSigType::NORMAL);
                  newTs->setParent(parent);
                  newTs->setTrack(e->track());
                  newTs->layout();

                  if ((newName->width() > lineWidthName) && (newName->xmlText() != ""))
                        lineWidthName = newName->width();

                  if (newTs->width() > _widthTimeSig)
                        _widthTimeSig = newTs->width();

                  delete newClef;
                  delete newName;
                  delete newKs;
                  delete newTs;
                 }
            }

      _leftMarginTotal = _score->styleP(Sid::clefLeftMargin);
      _leftMarginTotal += _score->styleP(Sid::keysigLeftMargin);
      _leftMarginTotal += _score->styleP(Sid::timesigLeftMargin);

      _newWidth = _widthClef + _widthKeySig + _widthTimeSig + _leftMarginTotal + _panelRightPadding;
      _xPosMeasure -= _offsetPanel;

      lineWidthName += _score->spatium() + _score->styleP(Sid::clefLeftMargin) + _widthClef;
      if (_newWidth < lineWidthName) {
            _newWidth = lineWidthName;
            _oldWidth = 0;
            }
      if (_oldWidth == 0) {
            _oldWidth = _newWidth;
            _width = _newWidth;
            }
      else if (_newWidth > 0) {
            if (_newWidth == _width) {
                  _oldWidth = _width;
                  _width = _newWidth;
                  }
            else if (((_xPosMeasure <= _newWidth) && (_xPosMeasure >= _oldWidth)) ||
                     ((_xPosMeasure >= _newWidth) && (_xPosMeasure <= _oldWidth)))
                        _width = _xPosMeasure;
            else if (((_xPosMeasure+_measureWidth <= _newWidth) && (_xPosMeasure+_measureWidth >= _oldWidth)) ||
                     ((_xPosMeasure+_measureWidth >= _newWidth) && (_xPosMeasure+_measureWidth <= _oldWidth)))
                        _width = _xPosMeasure+_measureWidth;
            else {
                  _oldWidth = _width;
                  _width = _newWidth;
                  }
            }

      _rect = QRect(0, _y, _width, _height);

      //====================

      painter.save();

      // Draw colored rectangle
      painter.setClipping(false);
      QPointF pos(_offsetPanel, 0);

      painter.translate(pos);
      QPen pen;
      pen.setWidthF(0.0);
      pen.setStyle(Qt::NoPen);
      painter.setPen(pen);
      painter.setBrush(preferences.getColor(PREF_UI_CANVAS_FG_COLOR));
      QRectF bg(_rect);

      bg.setWidth(_widthClef + _widthKeySig + _widthTimeSig + _leftMarginTotal + _panelRightPadding);
      QPixmap* fgPixmap = _sv->fgPixmap();
      if (fgPixmap == 0 || fgPixmap->isNull())
            painter.fillRect(bg, preferences.getColor(PREF_UI_CANVAS_FG_COLOR));
      else {
            painter.setMatrixEnabled(false);
            painter.drawTiledPixmap(bg, *fgPixmap, bg.topLeft()
               - QPoint(lrint(_sv->matrix().dx()), lrint(_sv->matrix().dy())));
            painter.setMatrixEnabled(true);
            }

      painter.setClipRect(_rect);
      painter.setClipping(true);

      QColor color(MScore::layoutBreakColor);

      // Draw measure text number
      // TODO: simplify (no Text element)
      QString text = QString("#%1").arg(_currentMeasure->no()+1);
      Text* newElement = new Text(_score);
      newElement->setFlag(ElementFlag::MOVABLE, false);
      newElement->setXmlText(text);
      newElement->setFamily("FreeSans");
      newElement->setSizeIsSpatiumDependent(true);
      newElement->setColor(color);
      newElement->layout1();
      pos = QPointF(_score->styleP(Sid::clefLeftMargin) + _widthClef, _y + newElement->height());
      painter.translate(pos);
      newElement->draw(&painter);
      pos += QPointF(_offsetPanel, 0);
      painter.translate(-pos);
      delete newElement;

      // This second pass draws the elements spaced evently using the width of the largest element
      for (const Element* e : el) {
            if (!e->visible() && !_score->showInvisible())
                  continue;

            if (e->isRest() && toRest(e)->isGap())
                  continue;

            if (e->isStaffLines()) {
                  painter.save();
                  Staff* currentStaff = _score->staff(e->staffIdx());
                  Segment* parent = _score->tick2segmentMM(tick);

                  pos = QPointF (_offsetPanel, e->pagePos().y());
                  painter.translate(pos);

                  // Draw staff lines
                  StaffLines newStaffLines(*toStaffLines(e));
                  newStaffLines.setParent(parent);
                  newStaffLines.setTrack(e->track());
                  newStaffLines.layout();
                  newStaffLines.setColor(color);
                  newStaffLines.setWidth(bg.width());
                  newStaffLines.draw(&painter);

                  // Draw barline
                  BarLine barLine(_score);
                  barLine.setBarLineType(BarLineType::NORMAL);
                  barLine.setParent(parent);
                  barLine.setTrack(e->track());
                  barLine.setSpanStaff(currentStaff->barLineSpan());
                  barLine.setSpanFrom(currentStaff->barLineFrom());
                  barLine.setSpanTo(currentStaff->barLineTo());
                  barLine.layout();
                  barLine.setColor(color);
                  barLine.draw(&painter);

                  // Draw the current staff name
                  QList<StaffName>& staffNamesLong = currentStaff->part()->instrument()->longNames();
                  QString staffName = staffNamesLong.isEmpty() ? " " : staffNamesLong[0].name();
                  if (staffName == "") {
                        QList<StaffName>& staffNamesShort = currentStaff->part()->instrument()->shortNames();
                        staffName = staffNamesShort.isEmpty() ? "" : staffNamesShort[0].name();
                        }

                  Text* newName = new Text(_score);
                  newName->setXmlText(staffName);
                  newName->setParent(parent);
                  newName->setTrack(e->track());
                  newName->setColor(color);
                  newName->setFamily("FreeSans");
                  newName->setSizeIsSpatiumDependent(true);
                  newName->layout();
                  newName->setPlainText(newName->plainText());
                  newName->layout();
                  if (currentStaff->part()->staff(0) == currentStaff) {
                        double _spatium = _score->spatium();
                        pos = QPointF (_score->styleP(Sid::clefLeftMargin) + _widthClef, -_spatium * 2);
                        painter.translate(pos);
                        newName->draw(&painter);
                        painter.translate(-pos);
                        }
                  delete newName;

                  qreal posX = 0.0;

                  // Draw the current Clef
                  Clef clef(_score);
                  clef.setClefType(currentStaff->clef(tick));
                  clef.setParent(parent);
                  clef.setTrack(e->track());
                  clef.setColor(color);
                  clef.layout();
                  posX += _score->styleP(Sid::clefLeftMargin);
                  clef.drawAt(&painter, QPointF(posX, clef.pos().y()));
                  posX += _widthClef;

                  // Draw the current KeySignature
                  KeySig newKs(_score);
                  newKs.setKeySigEvent(currentStaff->keySigEvent(tick));

                  // The Parent and the track must be set to have the key signature layout adjusted to different clefs
                  // This also adds naturals to the key signature (if set in the score style)
                  newKs.setParent(parent);
                  newKs.setTrack(e->track());
                  newKs.setColor(color);
                  newKs.setHideNaturals(true);
                  newKs.layout();
                  posX += _score->styleP(Sid::keysigLeftMargin);
                  newKs.drawAt(&painter, QPointF(posX, 0.0));

                  posX += _widthKeySig + _xPosTimeSig;

                  // Draw the current TimeSignature
                  TimeSig newTs(_score);

                  // Try to get local time signature, if not, get the current measure one
                  TimeSig* currentTimeSig = currentStaff->timeSig(tick);
                  if (currentTimeSig) {
                        newTs.setFrom(currentTimeSig);
                        newTs.setParent(parent);
                        newTs.setTrack(e->track());
                        newTs.setColor(color);
                        newTs.layout();
                        posX += _score->styleP(Sid::timesigLeftMargin);
                        newTs.drawAt(&painter, QPointF(posX, 0.0));
                        }
                  painter.restore();
                  }
            }
      painter.restore();
      _visible = true;
      }
WalletModel::SendCoinsReturn WalletModel::sendCoins(const QList<SendCoinsRecipient> &recipients, const CCoinControl *coinControl)
{
    qint64 total = 0;
    QSet<QString> setAddress;
    QString hex;

    if(recipients.empty())
    {
        return OK;
    }

    // Pre-check input data for validity
    foreach(const SendCoinsRecipient &rcp, recipients)
    {
        if(!validateAddress(rcp.address))
        {
            return InvalidAddress;
        }
        setAddress.insert(rcp.address);

        if(rcp.amount <= 0)
        {
            return InvalidAmount;
        }
        total += rcp.amount;
    }

    if(recipients.size() > setAddress.size())
    {
        return DuplicateAddress;
    }

    int64_t nBalance = 0;
    std::vector<COutput> vCoins;
    wallet->AvailableCoins(vCoins, true, coinControl);

    BOOST_FOREACH(const COutput& out, vCoins)
        nBalance += out.tx->vout[out.i].nValue;

    if(total > nBalance)
    {
        return AmountExceedsBalance;
    }

    if((total + nTransactionFee) > nBalance)
    {
        return SendCoinsReturn(AmountWithFeeExceedsBalance, nTransactionFee);
    }

	std::string txid = "";
	std::string messages = "";
	std::string hashBoinc = "";

    {
        LOCK2(cs_main, wallet->cs_wallet);

        // Sendmany
        std::vector<std::pair<CScript, int64_t> > vecSend;
		bool coinTracking = false;
		foreach(const SendCoinsRecipient &rcp, recipients)
        {
            CScript scriptPubKey;
            scriptPubKey.SetDestination(CBitcoinAddress(rcp.address.toStdString()).Get());
            vecSend.push_back(make_pair(scriptPubKey, rcp.amount));
			if (rcp.CoinTracking) coinTracking=true;
			messages += "<MESSAGE>" + AdvancedCrypt(FromQStringW(rcp.Message)) + "</MESSAGE>";
        
        }

        CWalletTx wtx;
        CReserveKey keyChange(wallet);
        int64_t nFeeRequired = 0;
		if (coinTracking)
		{
			printf("Creating tracked tx : old hashboinc %s",wtx.hashBoinc.c_str());
			wtx.hashBoinc = "<TRACK>" + wtx.GetHash().ToString() + "</TRACK>";
			//Run time code execution feature - 12-7-2014
			std::string q = "\"";
			std::string code = "MsgBox(" + q + "Hello!" + q + ",MsgBoxStyle.Critical," + q + "Message Title" + q + ")\r\n";
			wtx.hashBoinc += "<CODE>" + code + "</CODE>";
		}

		if (!msAttachmentGuid.empty())
		{
				printf("Adding attachment to tx %s",wtx.hashBoinc.c_str());
				wtx.hashBoinc += "<ATTACHMENT><TXID>" + wtx.GetHash().ToString() + "</TXID><ATTACHMENTGUID>" + msAttachmentGuid + "</ATTACHMENTGUID></ATTACHMENT>";
		}
		wtx.hashBoinc += messages;
		bool fCreated = wallet->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired, coinControl);

        if(!fCreated)
        {
            if((total + nFeeRequired) > nBalance) // FIXME: could cause collisions in the future
            {
                return SendCoinsReturn(AmountWithFeeExceedsBalance, nFeeRequired);
            }
            return TransactionCreationFailed;
        }
       
		if (coinTracking)
		{
			printf("Tracking hashBoinc %s",wtx.hashBoinc.c_str());
		}
		
		
		std::string samt = FormatMoney(wtx.vout[0].nValue);
		double dblAmt = dblFromAmount(wtx.vout[0].nValue);
	

        if(!uiInterface.ThreadSafeAskFee(nFeeRequired, tr("Sending...").toStdString()))
        {
            return Aborted;
        }
        if(!wallet->CommitTransaction(wtx, keyChange))
        {
            return TransactionCommitFailed;
        }
        hex = QString::fromStdString(wtx.GetHash().GetHex());
		txid = wtx.GetHash().GetHex();
		hashBoinc = wtx.hashBoinc;
    }
Esempio n. 29
0
WalletModel::SendCoinsReturn WalletModel::prepareTransaction(WalletModelTransaction &transaction, const CCoinControl *coinControl)
{
    CAmount total = 0;
    bool fSubtractFeeFromAmount = false;
    QList<SendCoinsRecipient> recipients = transaction.getRecipients();
    std::vector<CRecipient> vecSend;

    if(recipients.empty())
    {
        return OK;
    }

    QSet<QString> setAddress; // Used to detect duplicates
    int nAddresses = 0;

    // Pre-check input data for validity
    Q_FOREACH(const SendCoinsRecipient &rcp, recipients)
    {
        if (rcp.fSubtractFeeFromAmount)
            fSubtractFeeFromAmount = true;

        if (rcp.paymentRequest.IsInitialized())
        {   // PaymentRequest...
            CAmount subtotal = 0;
            const payments::PaymentDetails& details = rcp.paymentRequest.getDetails();
            for (int i = 0; i < details.outputs_size(); i++)
            {
                const payments::Output& out = details.outputs(i);
                if (out.amount() <= 0) continue;
                subtotal += out.amount();
                const unsigned char* scriptStr = (const unsigned char*)out.script().data();
                CScript scriptPubKey(scriptStr, scriptStr+out.script().size());
                CAmount nAmount = out.amount();
                CRecipient recipient = {scriptPubKey, nAmount, rcp.fSubtractFeeFromAmount};
                vecSend.push_back(recipient);
            }
            if (subtotal <= 0)
            {
                return InvalidAmount;
            }
            total += subtotal;
        }
        else
        {   // User-entered bitcoin address / amount:
            if(!validateAddress(rcp.address))
            {
                return InvalidAddress;
            }
            if(rcp.amount <= 0)
            {
                return InvalidAmount;
            }
            setAddress.insert(rcp.address);
            ++nAddresses;

            CScript scriptPubKey = GetScriptForDestination(CBitcoinAddress(rcp.address.toStdString()).Get());
            CRecipient recipient = {scriptPubKey, rcp.amount, rcp.fSubtractFeeFromAmount};
            vecSend.push_back(recipient);

            total += rcp.amount;
        }
    }
    if(setAddress.size() != nAddresses)
    {
        return DuplicateAddress;
    }

    CAmount nBalance = getBalance(coinControl);

    if(total > nBalance)
    {
        return AmountExceedsBalance;
    }

    {
        LOCK2(cs_main, wallet->cs_wallet);

        transaction.newPossibleKeyChange(wallet);

        CAmount nFeeRequired = 0;
        int nChangePosRet = -1;
        std::string strFailReason;

        CWalletTx *newTx = transaction.getTransaction();
        CReserveKey *keyChange = transaction.getPossibleKeyChange();
        bool fCreated = wallet->CreateTransaction(vecSend, *newTx, *keyChange, nFeeRequired, nChangePosRet, strFailReason, coinControl);
        transaction.setTransactionFee(nFeeRequired);
        if (fSubtractFeeFromAmount && fCreated)
            transaction.reassignAmounts(nChangePosRet);

        if(!fCreated)
        {
            if(!fSubtractFeeFromAmount && (total + nFeeRequired) > nBalance)
            {
                return SendCoinsReturn(AmountWithFeeExceedsBalance);
            }
            Q_EMIT message(tr("Send Coins"), QString::fromStdString(strFailReason),
                         CClientUIInterface::MSG_ERROR);
            return TransactionCreationFailed;
        }

        // reject absurdly high fee. (This can never happen because the
        // wallet caps the fee at maxTxFee. This merely serves as a
        // belt-and-suspenders check)
        if (nFeeRequired > maxTxFee)
            return AbsurdFee;
    }

    return SendCoinsReturn(OK);
}
Esempio n. 30
0
bool DigitizerSetTreeItem::addData(const FIFFLIB::FiffDigPointSet& tDigitizer, Qt3DCore::QEntity* parent)
{
    bool state = false;

    //parsing the digitizer List
    QList<FIFFLIB::FiffDigPoint> tNasion;
    QList<FIFFLIB::FiffDigPoint> tLAP;
    QList<FIFFLIB::FiffDigPoint> tRAP;
    QList<FIFFLIB::FiffDigPoint> tHpi;
    QList<FIFFLIB::FiffDigPoint> tEeg;
    QList<FIFFLIB::FiffDigPoint> tExtra;

    for(int i = 0; i < tDigitizer.size(); ++i){
        switch (tDigitizer[i].kind) {
        case FIFFV_POINT_CARDINAL:
            switch (tDigitizer[i].ident) {
            case FIFFV_POINT_LPA:
                tLAP.append(tDigitizer[i]);
            break;
            case FIFFV_POINT_NASION:
                tNasion.append(tDigitizer[i]);
            break;
            case FIFFV_POINT_RPA:
                tRAP.append(tDigitizer[i]);
            break;
            default:
            break;
            }
            break;
        case FIFFV_POINT_HPI:
            tHpi.append(tDigitizer[i]);
            break;
        case FIFFV_POINT_EEG:
            tEeg.append(tDigitizer[i]);
            break;
        case FIFFV_POINT_EXTRA:
            tExtra.append(tDigitizer[i]);
            break;
        default:
            break;
        }
    }

    // Find the Digitizer Items
    QList<QStandardItem*> itemList = this->findChildren(Data3DTreeModelItemTypes::DigitizerItem);

    if (!tLAP.empty()){
        //Create a LAP digitizer item
        DigitizerTreeItem* digitizerItem = new DigitizerTreeItem(Data3DTreeModelItemTypes::DigitizerItem,"LAP");
        state = digitizerItem->addData(tLAP, parent);
        itemList << digitizerItem;
        itemList << new QStandardItem(digitizerItem->toolTip());
        this->appendRow(itemList);
        itemList.clear();
    }
    if (!tNasion.empty()){
        //Create a Nasion digitizer item
        DigitizerTreeItem* digitizerItem = new DigitizerTreeItem(Data3DTreeModelItemTypes::DigitizerItem,"Nasion");
        state = digitizerItem->addData(tNasion, parent);
        itemList << digitizerItem;
        itemList << new QStandardItem(digitizerItem->toolTip());
        this->appendRow(itemList);
        itemList.clear();
    }
    if (!tRAP.empty()){
        //Create a RAO digitizer item
        DigitizerTreeItem* digitizerItem = new DigitizerTreeItem(Data3DTreeModelItemTypes::DigitizerItem,"RAP");
        state = digitizerItem->addData(tRAP, parent);
        itemList << digitizerItem;
        itemList << new QStandardItem(digitizerItem->toolTip());
        this->appendRow(itemList);
        itemList.clear();
    }
    if (!tHpi.empty()){
        //Create a HPI digitizer item
        DigitizerTreeItem* digitizerItem = new DigitizerTreeItem(Data3DTreeModelItemTypes::DigitizerItem,"HPI");
        state = digitizerItem->addData(tHpi, parent);
        itemList << digitizerItem;
        itemList << new QStandardItem(digitizerItem->toolTip());
        this->appendRow(itemList);
        itemList.clear();
    }
    if (!tEeg.empty()){
        //Create a EEG digitizer item
        DigitizerTreeItem* digitizerItem = new DigitizerTreeItem(Data3DTreeModelItemTypes::DigitizerItem,"EEG/ECG");
        state = digitizerItem->addData(tEeg, parent);
        itemList << digitizerItem;
        itemList << new QStandardItem(digitizerItem->toolTip());
        this->appendRow(itemList);
        itemList.clear();
    }
    if (!tExtra.empty()){
        //Create a extra digitizer item
        DigitizerTreeItem* digitizerItem = new DigitizerTreeItem(Data3DTreeModelItemTypes::DigitizerItem,"Extra");
        state = digitizerItem->addData(tExtra, parent);
        itemList << digitizerItem;
        itemList << new QStandardItem(digitizerItem->toolTip());
        this->appendRow(itemList);
        itemList.clear();
    }
    return state;
}