Example #1
0
Palette* MuseScore::newLinesPalette()
{
    Palette* sp = new Palette;
    sp->setName(QT_TRANSLATE_NOOP("Palette", "Lines"));
    sp->setMag(.8);
    sp->setGrid(82, 35);
    sp->setDrawGrid(true);

    qreal w = gscore->spatium() * 8;

    Slur* slur = new Slur(gscore);
    slur->setId(0);
    sp->append(slur, qApp->translate("lines", "Slur"));

    Hairpin* gabel0 = new Hairpin(gscore);
    gabel0->setHairpinType(Hairpin::CRESCENDO);
    gabel0->setLen(w);
    sp->append(gabel0, qApp->translate("lines", "Crescendo"));

    Hairpin* gabel1 = new Hairpin(gscore);
    gabel1->setHairpinType(Hairpin::DECRESCENDO);
    gabel1->setLen(w);
    sp->append(gabel1, QT_TRANSLATE_NOOP("Palette", "Diminuendo"));

    Volta* volta = new Volta(gscore);
    volta->setVoltaType(VoltaType::CLOSED);
    volta->setLen(w);
    volta->setText("1.");
    QList<int> il;
    il.append(1);
    volta->setEndings(il);
    sp->append(volta, QT_TRANSLATE_NOOP("Palette", "Prima volta"));

    volta = new Volta(gscore);
    volta->setVoltaType(VoltaType::CLOSED);
    volta->setLen(w);
    volta->setText("2.");
    il.clear();
    il.append(2);
    volta->setEndings(il);
    sp->append(volta, QT_TRANSLATE_NOOP("Palette", "Seconda volta"));

    volta = new Volta(gscore);
    volta->setVoltaType(VoltaType::CLOSED);
    volta->setLen(w);
    volta->setText("3.");
    il.clear();
    il.append(3);
    volta->setEndings(il);
    sp->append(volta, QT_TRANSLATE_NOOP("Palette", "Terza volta"));

    volta = new Volta(gscore);
    volta->setVoltaType(VoltaType::OPEN);
    volta->setLen(w);
    volta->setText("2.");
    il.clear();
    il.append(2);
    volta->setEndings(il);
    sp->append(volta, QT_TRANSLATE_NOOP("Palette", "Seconda volta 2"));

    Ottava* ottava = new Ottava(gscore);
    ottava->setOttavaType(OttavaType::OTTAVA_8VA);
    ottava->setLen(w);
    sp->append(ottava, QT_TRANSLATE_NOOP("Palette", "8va"));

    ottava = new Ottava(gscore);
    ottava->setOttavaType(OttavaType::OTTAVA_8VB);
    ottava->setLen(w);
    ottava->setPlacement(Element::BELOW);
    sp->append(ottava, QT_TRANSLATE_NOOP("Palette", "8vb"));

    ottava = new Ottava(gscore);
    ottava->setOttavaType(OttavaType::OTTAVA_15MA);
    ottava->setLen(w);
    sp->append(ottava, QT_TRANSLATE_NOOP("Palette", "15ma"));

    ottava = new Ottava(gscore);
    ottava->setOttavaType(OttavaType::OTTAVA_15MB);
    ottava->setLen(w);
    ottava->setPlacement(Element::BELOW);
    sp->append(ottava, QT_TRANSLATE_NOOP("Palette", "15mb"));

    ottava = new Ottava(gscore);
    ottava->setOttavaType(OttavaType::OTTAVA_22MA);
    ottava->setLen(w);
    sp->append(ottava, QT_TRANSLATE_NOOP("Palette", "22ma"));

    ottava = new Ottava(gscore);
    ottava->setOttavaType(OttavaType::OTTAVA_22MB);
    ottava->setLen(w);
    sp->append(ottava, QT_TRANSLATE_NOOP("Palette", "22mb"));


    Pedal* pedal = new Pedal(gscore);
    pedal->setLen(w);
    sp->append(pedal, QT_TRANSLATE_NOOP("Palette", "Pedal"));

    pedal = new Pedal(gscore);
    pedal->setLen(w);
    pedal->setEndHookType(HOOK_45);
    sp->append(pedal, QT_TRANSLATE_NOOP("Palette", "Pedal"));

    pedal = new Pedal(gscore);
    pedal->setLen(w);
    pedal->setBeginSymbol(SymId::noSym);
    pedal->setBeginHook(true);
    pedal->setBeginHookType(HOOK_45);
    pedal->setEndHookType(HOOK_45);
    sp->append(pedal, QT_TRANSLATE_NOOP("Palette", "Pedal"));

    pedal = new Pedal(gscore);
    pedal->setLen(w);
    pedal->setBeginSymbol(SymId::noSym);
    pedal->setBeginHook(true);
    pedal->setBeginHookType(HOOK_45);
    sp->append(pedal, QT_TRANSLATE_NOOP("Palette", "Pedal"));

    Trill* trill = new Trill(gscore);
    trill->setLen(w);
    sp->append(trill, QT_TRANSLATE_NOOP("Palette", "Trill line"));

    trill = new Trill(gscore);
    trill->setTrillType("upprall");
    trill->setLen(w);
    sp->append(trill, QT_TRANSLATE_NOOP("Palette", "Upprall line"));

    trill = new Trill(gscore);
    trill->setTrillType("downprall");
    trill->setLen(w);
    sp->append(trill, QT_TRANSLATE_NOOP("Palette", "Downprall line"));

    trill = new Trill(gscore);
    trill->setTrillType("prallprall");
    trill->setLen(w);
    sp->append(trill, QT_TRANSLATE_NOOP("Palette", "Prallprall line"));

    trill = new Trill(gscore);
    trill->setTrillType("pure");
    trill->setLen(w);
    sp->append(trill, QT_TRANSLATE_NOOP("Palette", "Wavy line"));

    TextLine* textLine = new TextLine(gscore);
    textLine->setLen(w);
    textLine->setBeginText("VII", gscore->textStyle(TEXT_STYLE_TEXTLINE));
    textLine->setEndHook(true);
    sp->append(textLine, QT_TRANSLATE_NOOP("Palette", "Text line"));

    TextLine* line = new TextLine(gscore);
    line->setLen(w);
    line->setDiagonal(true);
    sp->append(line, QT_TRANSLATE_NOOP("Palette", "Line"));

    Ambitus* a = new Ambitus(gscore);
    sp->append(a, QT_TRANSLATE_NOOP("Palette", "Ambitus"));

    return sp;
}
Example #2
0
void StandGrapher::createGui()
{
    //--------------------------------------------------
    // Universal button creator for the navigation bars
    //--------------------------------------------------
    class ButtonCreator
    {
    public:
        static QPushButton * create(QWidget * parent, const QString & objName, const QIcon & icon,
            const QKeySequence & key, QString toolTip, QWidget * target, const char * slot)
        {
            QPushButton * button = new QPushButton(parent);
            button->setObjectName(objName);
            button->setFocusPolicy(Qt::NoFocus);
            connect(button, SIGNAL(pressed()), target, slot);

            button->setIconSize(QSize(32, 32));
            button->setIcon(QIcon(icon));

            if (!key.isEmpty())
                toolTip += " " + tr("(Shortcut: <b>%1</b>)").arg(key.toString());
            button->setToolTip(toolTip);

            QShortcut * shortcut = new QShortcut(key, target);
            connect(shortcut, SIGNAL(activated()), target, slot);

            return button;
        }
    };

    QList<QPushButton *> buttons;

    //-------------------------------------------
    // Horizontal tool box
    //-------------------------------------------

    hToolBox = new QFrame(this);
    hToolBox->setFrameStyle(QFrame::StyledPanel | QFrame::Plain);
    hToolBox->setAutoFillBackground(true);
    hToolBox->setCursor(Qt::ArrowCursor);
    hToolBox->installEventFilter(this);

    // Create buttons
    buttons << ButtonCreator::create(hToolBox, "Start_button", QIcon(":/start.png"),
        Qt::Key_Home, tr("Start"), this, SLOT(slotStart()));
    buttons << ButtonCreator::create(hToolBox, "Prev_button", QIcon(":/previous.png"),
        Qt::Key_Left, tr("Previous"), this, SLOT(slotPrevious()));
    buttons << ButtonCreator::create(hToolBox, "HFit_button", QIcon(":/fit.png"),
        QKeySequence(), tr("Fit horizontally"), this, SLOT(slotFit()));
    buttons << ButtonCreator::create(hToolBox, "Next_button", QIcon(":/next.png"),
        Qt::Key_Right, tr("Next"), this, SLOT(slotNext()));
    buttons << ButtonCreator::create(hToolBox, "Finish_button", QIcon(":/finish.png"),
        Qt::Key_End, tr("End"), this, SLOT(slotEnd()));
    buttons << ButtonCreator::create(hToolBox, "HZoomIn_button", QIcon(":/plus.png"),
        Qt::Key_Plus, tr("Wider"), this, SLOT(slotZoomIn()));
    buttons << ButtonCreator::create(hToolBox, "HZoomOut_button", QIcon(":/minus.png"),
        Qt::Key_Minus, tr("Narrower"), this, SLOT(slotZoomOut()));

    // Layout buttons
    QHBoxLayout * hLayout = new QHBoxLayout(hToolBox);
    foreach(QPushButton * button, buttons)
        hLayout->addWidget(button);
    hToolBox->setLayout(hLayout);

    //-------------------------------------------
    // Vertical tool box
    //-------------------------------------------

    vToolBox = new QFrame(this);
    vToolBox->setFrameStyle(QFrame::StyledPanel | QFrame::Plain);
    vToolBox->setAutoFillBackground(true);
    vToolBox->setCursor(Qt::ArrowCursor);
    vToolBox->installEventFilter(this);

    buttons.clear();
    buttons << ButtonCreator::create(vToolBox, "Up_button", QIcon(":/up.png"),
        Qt::Key_Up, tr("Up"), this, SLOT(slotUp()));
    buttons << ButtonCreator::create(vToolBox, "VFit_button", QIcon(":/fit_vert.png"),
        QKeySequence(), tr("Fit vertically"), this, SLOT(slotVFit()));
    buttons << ButtonCreator::create(vToolBox, "Down_button", QIcon(":/down.png"),
        Qt::Key_Down, tr("Down"), this, SLOT(slotDown()));
    buttons << ButtonCreator::create(vToolBox, "VZoomIn_button", QIcon(":/plus.png"),
        Qt::SHIFT+Qt::Key_Plus, tr("Wider"), this, SLOT(slotVZoomIn()));
    buttons << ButtonCreator::create(vToolBox, "VZoomOut_button", QIcon(":/minus.png"),
        Qt::SHIFT+Qt::Key_Minus, tr("Narrower"), this, SLOT(slotVZoomOut()));

    // Layout buttons
    QVBoxLayout * vLayout = new QVBoxLayout(vToolBox);
    foreach(QPushButton * button, buttons)
        vLayout->addWidget(button);
    vToolBox->setLayout(vLayout);

    //-------------------------------------------
    // Tool Box
    //-------------------------------------------

    toolBox = new QFrame(this);
    toolBox->setFrameStyle(QFrame::StyledPanel | QFrame::Plain);
    toolBox->setAutoFillBackground(true);
    toolBox->setCursor(Qt::ArrowCursor);
    toolBox->installEventFilter(this);

    buttons.clear();

    // Filter button
    filterButton = new QPushButton(toolBox);
    filterButton->setIcon(QIcon(":/filter.png"));
    filterButton->setCheckable(true);
    filterButton->setShortcut(Qt::Key_F);
    filterButton->setToolTip(tr("Filter window"));
    connect(filterButton, SIGNAL(released()), this, SLOT(slotFilterWindow()));
    buttons << filterButton;

    filterWindow = new ParamsFilterWidget(this);

    connect(filterWindow, SIGNAL( modelChanged(Stand_trace_model::Ptr) ),
        this, SLOT( setModel(Stand_trace_model::Ptr) ));

    connect(filterWindow, SIGNAL(windowClosed()),
        filterButton, SLOT(toggle()));

    // Drawing lines option
    drawLinesButton = new QPushButton(toolBox);
    drawLinesButton->setIcon(QIcon(":/draw_lines.png"));
    drawLinesButton->setCheckable(true);
    drawLinesButton->setChecked(true);
    drawLinesButton->setShortcut(Qt::Key_L);
    drawLinesButton->setToolTip(tr("Draw lines"));
    connect(drawLinesButton, SIGNAL(released()), this, SLOT(slotDrawLineSwither()));
    buttons << drawLinesButton;

    // Antialiasing option
    antialiasingButton = new QPushButton(toolBox);
    antialiasingButton->setIcon(QIcon(":/antialiasing.png"));
    antialiasingButton->setCheckable(true);
    antialiasingButton->setChecked(antialiasing);
    antialiasingButton->setShortcut(Qt::Key_A);
    antialiasingButton->setToolTip(tr("Antialiasing"));
    connect(antialiasingButton, SIGNAL(clicked(bool)), this, SLOT(slotAntialiasingSwither(bool)));
    buttons << antialiasingButton;

    // Print button
    printButton = new QPushButton(toolBox);
    printButton->setIcon(QIcon(":/printer.png"));
    printButton->setShortcut(Qt::Key_P);
    printButton->setToolTip(tr("Print"));
    connect(printButton, SIGNAL(released()), this, SLOT(slotPrintGraph()));
    buttons << printButton;

    // Setup buttons
    foreach (QPushButton * button, buttons) {
        button->setIconSize(QSize(16, 16));
        button->setFocusPolicy(Qt::NoFocus);
        button->setToolTip(button->toolTip() + " " +
            tr("(Shortcut: <b>%1</b>)").arg(button->shortcut().toString()));
    }
    void refreshEscrowTable(EscrowModelType type)
    {

        cachedEscrowTable.clear();
        {
			string strMethod = string("escrowlist");
	        UniValue params(UniValue::VARR); 
			UniValue result ;
			string name_str;
			string time_str;
			string seller_str;
			string arbiter_str;
			string status_str;
			string offeraccept_str;
			string offer_str;
			string offertitle_str;
			string total_str;
			string buyer_str;
			int unixTime;
			QDateTime dateTime;	
			try {
				result = tableRPC.execute(strMethod, params);
				if (result.type() == UniValue::VARR)
				{
					name_str = "";
					time_str = "";
					seller_str = "";
					arbiter_str = "";
					status_str = "";
					offeraccept_str = "";
					offer_str = "";
					offertitle_str = "";
					total_str = "";	
					buyer_str = "";
					const UniValue &arr = result.get_array();
				    for (unsigned int idx = 0; idx < arr.size(); idx++) {
					    const UniValue& input = arr[idx];
						if (input.type() != UniValue::VOBJ)
							continue;
						const UniValue& o = input.get_obj();
						name_str = "";
						name_str = "";
						seller_str = "";
						arbiter_str = "";
						status_str = "";
						offeraccept_str = "";
						offer_str = "";
						total_str = "";
			
				
						const UniValue& name_value = find_value(o, "escrow");
						if (name_value.type() == UniValue::VSTR)
							name_str = name_value.get_str();
						const UniValue& time_value = find_value(o, "time");
						if (time_value.type() == UniValue::VSTR)
							time_str = time_value.get_str();
						const UniValue& seller_value = find_value(o, "seller");
						if (seller_value.type() == UniValue::VSTR)
							seller_str = seller_value.get_str();
						const UniValue& arbiter_value = find_value(o, "arbiter");
						if (arbiter_value.type() == UniValue::VSTR)
							arbiter_str = arbiter_value.get_str();
						const UniValue& buyer_value = find_value(o, "buyer");
						if (buyer_value.type() == UniValue::VSTR)
							buyer_str = buyer_value.get_str();
						const UniValue& offer_value = find_value(o, "offer");
						if (offer_value.type() == UniValue::VSTR)
							offer_str = offer_value.get_str();
						const UniValue& offertitle_value = find_value(o, "offertitle");
						if (offertitle_value.type() == UniValue::VSTR)
							offertitle_str = offertitle_value.get_str();
						const UniValue& offeraccept_value = find_value(o, "offeracceptlink");
						if (offeraccept_value.type() == UniValue::VSTR)
							offeraccept_str = offeraccept_value.get_str();
						const UniValue& total_value = find_value(o, "total");
						if (total_value.type() == UniValue::VSTR)
							total_str = total_value.get_str();
						const UniValue& status_value = find_value(o, "status");
						if (status_value.type() == UniValue::VSTR)
							status_str = status_value.get_str();
						
						unixTime = atoi(time_str.c_str());
						dateTime.setTime_t(unixTime);
						time_str = dateTime.toString().toStdString();	

						updateEntry(QString::fromStdString(name_str), QString::fromStdString(time_str), QString::fromStdString(seller_str), QString::fromStdString(arbiter_str), QString::fromStdString(offer_str), QString::fromStdString(offertitle_str), QString::fromStdString(offeraccept_str), QString::fromStdString(total_str), QString::fromStdString(status_str), QString::fromStdString(buyer_str), type, CT_NEW); 
					}
				}
 			}
			catch (UniValue& objError)
			{
				return;
			}
			catch(std::exception& e)
			{
				return;
			}           
         }
        // qLowerBound() and qUpperBound() require our cachedEscrowTable list to be sorted in asc order
        qSort(cachedEscrowTable.begin(), cachedEscrowTable.end(), EscrowTableEntryLessThan());
    }
Example #4
0
//! This function corrects the DNs in a given brick.
//! It also stores results in frameletOffsetsForBand every time the
//! band changes so it doesn't have to re-project at every framelet.
//! Equivalent changes are calculated for the next framelet... that is,
//! equivalent pixels. This function both calculates and applies these.
void RemoveSeam(Buffer &out, int framelet, int band,
                bool matchIsEven) {
  // Apply fixes from last pass. Basically all changes happen in two
  //   places, because the DNs exist in two cubes, this is the second
  //   place.
  for(int fix = 0; fix < nextFrameletFixes.size(); fix ++) {
    QPair<int, int> fixLoc = nextFrameletFixes[fix].first;
    double fixDn = nextFrameletFixes[fix].second;

    try {
      int outIndex = out.Index(fixLoc.first, fixLoc.second, band);
      out[outIndex] = fixDn;
    }
    catch(IException &) {
    }
  }

  nextFrameletFixes.clear();

  // Match == goodData. "goodData" is the top of the next framelet.
  Cube *goodDataCube = (matchIsEven) ? evenCube : oddCube;
  // "badData" is the bottom of the current framelet, what we were given.
  Cube *badDataCube  = (matchIsEven) ? oddCube  : evenCube;

  Camera *goodCam = goodDataCube->camera();
  Camera *badCam  = badDataCube->camera();

  // Verify we're at the correct band
  goodCam->SetBand(band);
  badCam->SetBand(band);

  // Absolute line number for top of framelets.
  int goodDataStart = frameletSize * (framelet + 1);
  int badDataStart = frameletSize * framelet;

  // Start corrections to the current brick at this line
  int badLineStart = goodDataStart - overlapSize - 1;
  // End corrections to the current brick at this line
  int badLineEnd = goodDataStart - 1;

  int offsetSample = 0;
  int offsetLine = 0;

  // Loop left to right, top to bottom of problematic area at bottom of framelet
  for(int badLine = badLineStart; badLine <= badLineEnd; badLine ++) {
    for(int sample = 1; sample <= out.SampleDimension(); sample ++) {
      // A fair good data weight is the % across problematic area so fair
      double goodDataWeight = (double)(badLine - badLineStart) /
                             (double)(badLineEnd - badLineStart);

      // But good data is good, so let's bias it towards the good data
      goodDataWeight *= 2;
      if(goodDataWeight > 1) goodDataWeight = 1;

      // Bad data weight is the inverse of the good data's weight.
      double badDataWeight = 1.0 - goodDataWeight;

      int outIndex = out.Index(sample, badLine, band);
      // This is the indexing scheme for frameletOffsetsForBand
      int optimizeIndex = (badLine - badLineStart) * out.SampleDimension() +
                          sample - 1;

      // Does the optimized (pre-calculated) translation from bad to good
      //  exist?
      if(optimizeIndex < frameletOffsetsForBand.size()) {
        // This offset any good? If not then do nothing.
        if(!frameletOffsetsForBand[optimizeIndex].Valid())
          continue;

        // Use optimization!
        offsetSample = frameletOffsetsForBand[optimizeIndex].SampleOffset();
        offsetLine = frameletOffsetsForBand[optimizeIndex].LineOffset();

        ASSERT(frameletOffsetsForBand[optimizeIndex].Sample() == sample);
      }
      // There is no pre-calculated translation, calculate it
      else if(badCam->SetImage(sample, badLine)) {
        double lat = badCam->UniversalLatitude();
        double lon = badCam->UniversalLongitude();

        if(goodCam->SetUniversalGround(lat, lon)) {
          double goodSample = goodCam->Sample();
          double goodLine = goodCam->Line();

          // Set the current offset for correction
          offsetSample = (int)(goodSample - sample + 0.5);
          offsetLine = (int)(goodLine - badLine + 0.5);

          // Remember this calculation for future passes
          frameletOffsetsForBand.push_back(Offset(sample, badLine - badDataStart,
                                                  offsetSample, offsetLine));
        }
        else {
          // Don't do anything since we failed at this pixel; it will be copied
          //   from the input directly
          frameletOffsetsForBand.push_back(Offset());
          continue;
        }
      }

      // Translate current sample,line (bad) to (good) data's sample,line
      double goodSample = offsetSample + sample;
      double goodLine = offsetLine + badLine;

      // Get the pixel we're missing (good)
      Portal p(1, 1, goodDataCube->pixelType());
      p.SetPosition(goodSample, goodLine, band);
      goodDataCube->read(p);

      // Attempt to apply weighted average
      if(!Isis::IsSpecial(p[0]) && !Isis::IsSpecial(out[outIndex])) {
        out[outIndex] = p[0] * goodDataWeight + out[outIndex] * badDataWeight;
      }
      else if(!Isis::IsSpecial(p[0])) {
        out[outIndex] = p[0];
      }

      // Apply change to next framelet also
      QPair<int, int> fixLoc((int)(goodSample + 0.5),
                             (int)(goodLine   + 0.5));
      QPair< QPair<int, int>, double > fix(fixLoc, out[outIndex]);
      nextFrameletFixes.push_back(fix);
    }
  }
}
Example #5
0
// calculates the metatypes for the method
// the slot must have the parameters in the following form:
//  - zero or more value or const-ref parameters of any kind
//  - zero or one const ref of QDBusMessage
//  - zero or more non-const ref parameters
// No parameter may be a template.
// this function returns -1 if the parameters don't match the above form
// this function returns the number of *input* parameters, including the QDBusMessage one if any
// this function does not check the return type, so metaTypes[0] is always 0 and always present
// metaTypes.count() >= retval + 1 in all cases
//
// sig must be the normalised signature for the method
int qDBusParametersForMethod(const QMetaMethod &mm, QList<int>& metaTypes)
{
    QDBusMetaTypeId::init();

    QList<QByteArray> parameterTypes = mm.parameterTypes();
    metaTypes.clear();

    metaTypes.append(0);        // return type
    int inputCount = 0;
    bool seenMessage = false;
    QList<QByteArray>::ConstIterator it = parameterTypes.constBegin();
    QList<QByteArray>::ConstIterator end = parameterTypes.constEnd();
    for ( ; it != end; ++it) {
        const QByteArray &type = *it;
        if (type.endsWith('*')) {
            //qWarning("Could not parse the method '%s'", mm.signature());
            // pointer?
            return -1;
        }

        if (type.endsWith('&')) {
            QByteArray basictype = type;
            basictype.truncate(type.length() - 1);

            int id = qDBusNameToTypeId(basictype);
            if (id == 0) {
                //qWarning("Could not parse the method '%s'", mm.signature());
                // invalid type in method parameter list
                return -1;
            } else if (QDBusMetaType::typeToSignature(id) == 0)
                return -1;

            metaTypes.append( id );
            seenMessage = true; // it cannot appear anymore anyways
            continue;
        }

        if (seenMessage) {      // && !type.endsWith('&')
            //qWarning("Could not parse the method '%s'", mm.signature());
            // non-output parameters after message or after output params
            return -1;          // not allowed
        }

        int id = qDBusNameToTypeId(type);
        if (id == 0) {
            //qWarning("Could not parse the method '%s'", mm.signature());
            // invalid type in method parameter list
            return -1;
        }

        if (id == QDBusMetaTypeId::message)
            seenMessage = true;
        else if (QDBusMetaType::typeToSignature(id) == 0)
            return -1;

        metaTypes.append(id);
        ++inputCount;
    }

    return inputCount;
}
Example #6
0
void Settings::SetDefaultSettings()
{
    pMain->showMaximized();

    QList<int> intList;
    intList.append(qRound(pMain->GetUi()->splitter->height()*.5));
    intList.append(qRound(pMain->GetUi()->splitter->height()*.25));
    intList.append(qRound(pMain->GetUi()->splitter->height()*.25));

    pMain->GetUi()->splitter->setSizes(intList);

    intList.clear();

    intList.append(qRound(pMain->GetUi()->splitter->width()*.25));
    intList.append(qRound(pMain->GetUi()->splitter->width()*.75));

    pMain->GetUi()->rulesSplitter->setSizes(intList);

    intList.clear();

    intList.append(qRound(pMain->GetUi()->splitter->width()*.80));
    intList.append(qRound(pMain->GetUi()->splitter->width()*.20));

    pMain->GetUi()->browserSplitter->setSizes(intList);

    intList.clear();

    intList.append(50);
    intList.append(25);
    intList.append(25);
    intList.append(25);
    intList.append(600);
    intList.append(150);
    intList.append(100);
    intList.append(70);

    for(int i = 0; i < intList.size(); i++)
        pMain->GetUi()->browserTable->setColumnWidth(i, intList.at(i));

    pMain->GetUi()->browserTable->horizontalHeader()->setSectionResizeMode(1, QHeaderView::Fixed);
    pMain->GetUi()->browserTable->horizontalHeader()->setSectionResizeMode(2, QHeaderView::Fixed);
    pMain->GetUi()->browserTable->horizontalHeader()->setSectionResizeMode(3, QHeaderView::Fixed);
    pMain->GetUi()->browserTable->horizontalHeaderItem(5)->setTextAlignment(Qt::AlignLeft);
    pMain->GetUi()->browserTable->horizontalHeaderItem(6)->setTextAlignment(Qt::AlignLeft);

    intList.clear();

    intList.append(125);
    intList.append(125);

    for(int i = 0; i < intList.size(); i++)
        pMain->GetUi()->rulesTable->setColumnWidth(i, intList.at(i));

    intList.clear();

    intList.append(75);
    intList.append(225);
    intList.append(100);
    intList.append(150);
    intList.append(200);

    for(int i = 0; i < intList.size(); i++)
        pMain->GetUi()->playerTable->setColumnWidth(i, intList.at(i));

    qsrand((uint)(QTime::currentTime()).msec());
    pMain->u16logPort = qrand() % ((PORT_MAX + 1) - PORT_MIN) + PORT_MIN;

    pMain->showLoggingInfo = true;
}
Example #7
0
int QgsSnapper::snapMapPoint( const QgsPoint& mapCoordPoint, QList<QgsSnappingResult>& snappingResult, const QList<QgsPoint>& excludePoints )
{
  snappingResult.clear();

  QMultiMap<double, QgsSnappingResult> snappingResultList;//all snapping results
  QMultiMap<double, QgsSnappingResult> currentResultList; //snapping results of examined layer

  //start point in (output) map coordinates

  QgsPoint layerCoordPoint; //start point in layer coordinates
  QgsSnappingResult newResult;

  QList<QgsSnapper::SnapLayer>::iterator snapLayerIt;
  for ( snapLayerIt = mSnapLayers.begin(); snapLayerIt != mSnapLayers.end(); ++snapLayerIt )
  {
    if ( !snapLayerIt->mLayer->hasGeometryType() )
      continue;

    currentResultList.clear();
    //transform point from map coordinates to layer coordinates
    layerCoordPoint = mMapSettings.mapToLayerCoordinates( snapLayerIt->mLayer, mapCoordPoint );

    double tolerance = QgsTolerance::toleranceInMapUnits( snapLayerIt->mTolerance, snapLayerIt->mLayer, mMapSettings, snapLayerIt->mUnitType );
    if ( snapLayerIt->mLayer->snapWithContext( layerCoordPoint, tolerance,
         currentResultList, snapLayerIt->mSnapTo ) != 0 )
    {
      //error
    }

    //transform each result from layer crs to map crs (including distance)
    QMultiMap<double, QgsSnappingResult>::iterator currentResultIt;
    for ( currentResultIt = currentResultList.begin(); currentResultIt != currentResultList.end(); ++currentResultIt )
    {
      //for each snapping result: transform start point, snap point and other points into map coordinates to find out distance
      //store results in snapping result list
      newResult = currentResultIt.value();
      newResult.snappedVertex = mMapSettings.layerToMapCoordinates( snapLayerIt->mLayer, currentResultIt.value().snappedVertex );
      newResult.beforeVertex = mMapSettings.layerToMapCoordinates( snapLayerIt->mLayer, currentResultIt.value().beforeVertex );
      newResult.afterVertex = mMapSettings.layerToMapCoordinates( snapLayerIt->mLayer, currentResultIt.value().afterVertex );
      snappingResultList.insert( sqrt( newResult.snappedVertex.sqrDist( mapCoordPoint ) ), newResult );
    }
  }

  //excluded specific points from result
  cleanResultList( snappingResultList, excludePoints );

  //evaluate results according to snap mode
  QMultiMap<double, QgsSnappingResult>::iterator evalIt =  snappingResultList.begin();
  if ( evalIt == snappingResultList.end() )
  {
    return 0;
  }


  //Gives a priority to vertex snapping over segment snapping
  QgsSnappingResult returnResult = evalIt.value();
  for ( evalIt = snappingResultList.begin(); evalIt != snappingResultList.end(); ++evalIt )
  {
    if ( evalIt.value().snappedVertexNr != -1 )
    {
      returnResult = evalIt.value();
      snappingResultList.erase( evalIt );
      break;
    }
  }

  //We return the preferred result
  snappingResult.push_back( returnResult );

  if ( mSnapMode == QgsSnapper::SnapWithOneResult )
  {
    //return only a single  result, nothing more to do
  }
  else if ( mSnapMode == QgsSnapper::SnapWithResultsForSamePosition )
  {
    //take all snapping results within a certain tolerance because rounding differences may occur
    double tolerance = 0.000001;

    for ( evalIt = snappingResultList.begin(); evalIt != snappingResultList.end(); ++evalIt )
    {
      if ( returnResult.snappedVertex.sqrDist( evalIt.value().snappedVertex ) < tolerance*tolerance )
      {
        snappingResult.push_back( evalIt.value() );
      }
    }

  }

  else //take all results
  {
    for ( evalIt = snappingResultList.begin(); evalIt != snappingResultList.end(); ++evalIt )
    {
      snappingResult.push_back( evalIt.value() );
    }
  }

  return 0;
}
Example #8
0
// The index timer has expired.  Look for any unindexed notes or resources
void IndexRunner::index() {
    if (disableIndexing)
        return;

    if (!keepRunning || pauseIndexing) {
        return;
    }

    if (!init)
        initialize();

    indexTimer->stop();   // Stop the timer because we are already working
    indexTimer->setInterval(global.minIndexInterval);

    QList<qint32> lids;

    NoteTable noteTable(&db->conn);
    ResourceTable resourceTable(&db->conn);
    bool endMsgNeeded = false;

    int countPause = global.indexNoteCountPause;

    QList<qint32> finishedLids;
    // Get any unindexed notes
    if (keepRunning && !pauseIndexing && noteTable.getIndexNeeded(lids) > 0) {
        QApplication::processEvents();
        endMsgNeeded = true;
        QLOG_DEBUG() << "Unindexed Notes found: " << lids.size();

        // Index any undindexed note content.
        for (int i=0; keepRunning && !pauseIndexing && i<lids.size(); i++) {
            QApplication::processEvents();
            Note n;
            noteTable.get(n, lids[i], false, false);
            indexNote(lids[i],n);
            finishedLids.append(lids[i]);
            if (countPause <=0) {
                flushCache();
                for (int j=0; j<finishedLids.size(); j++)
                    noteTable.setIndexNeeded(finishedLids[j], false);
                indexTimer->start();
                return;
            }
            countPause--;
        }
    }
    if (keepRunning && !pauseIndexing)
       flushCache();
    for (int j=0; !pauseIndexing && keepRunning && j<finishedLids.size(); j++)
        noteTable.setIndexNeeded(finishedLids[j], false);


    lids.clear();  // Clear out the list so we can start on resources

    if (!keepRunning || pauseIndexing) {
        indexTimer->start();
        return;
    }

    countPause = global.indexResourceCountPause;
    finishedLids.clear();
    // Start indexing resources
    if (keepRunning && !pauseIndexing && resourceTable.getIndexNeeded(lids) > 0) {
        endMsgNeeded = true;

        // Index each resource that is needed.
        for (int i=0; keepRunning && !pauseIndexing && i<lids.size(); i++) {
            QApplication::processEvents();
            Resource r;
            resourceTable.get(r, lids.at(i), false);
            qint32 noteLid = noteTable.getLid(r.noteGuid);
            indexRecognition(noteLid, r);
            QString mime = "";
            if (r.mime.isSet())
                mime = r.mime;
            if (mime == "application/pdf")
                indexPdf(noteLid, r);
            else {
                if (mime.startsWith("application", Qt::CaseInsensitive))
                    indexAttachment(noteLid, r);
            }
            finishedLids.append(lids[i]);
            if (countPause <=0) {
                flushCache();
                for (int j=0; keepRunning && !pauseIndexing && j<finishedLids.size(); j++) {
                    resourceTable.setIndexNeeded(finishedLids[j], false);
                }
                indexTimer->start();
                return;
            }
            countPause--;
        }
    }
    if (!keepRunning || pauseIndexing) {
        indexTimer->start();
        return;
    }
    if (keepRunning && !pauseIndexing)
        flushCache();
    for (int j=0; keepRunning && !pauseIndexing && j<finishedLids.size(); j++) {
        resourceTable.setIndexNeeded(finishedLids[j], false);
    }

    if (endMsgNeeded) {
        QLOG_DEBUG() << "Indexing completed";
    }

    indexTimer->setInterval(global.maxIndexInterval);
    indexTimer->start();
}
Example #9
0
QVariantMap QgsDissolveAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback ) const
{
  std::unique_ptr< QgsFeatureSource > source( parameterAsSource( parameters, QStringLiteral( "INPUT" ), context ) );
  if ( !source )
    return QVariantMap();

  QString dest;
  std::unique_ptr< QgsFeatureSink > sink( parameterAsSink( parameters, QStringLiteral( "OUTPUT" ), context, source->fields(), QgsWkbTypes::multiType( source->wkbType() ), source->sourceCrs(), dest ) );

  if ( !sink )
    return QVariantMap();

  QStringList fields = parameterAsFields( parameters, QStringLiteral( "FIELD" ), context );

  long count = source->featureCount();
  if ( count <= 0 )
    return QVariantMap();

  QgsFeature f;
  QgsFeatureIterator it = source->getFeatures();

  double step = 100.0 / count;
  int current = 0;

  if ( fields.isEmpty() )
  {
    // dissolve all - not using fields
    bool firstFeature = true;
    // we dissolve geometries in blocks using unaryUnion
    QList< QgsGeometry > geomQueue;
    QgsFeature outputFeature;

    while ( it.nextFeature( f ) )
    {
      if ( feedback->isCanceled() )
      {
        break;
      }

      if ( firstFeature )
      {
        outputFeature = f;
        firstFeature = false;
      }

      if ( f.hasGeometry() && f.geometry() )
      {
        geomQueue.append( f.geometry() );
        if ( geomQueue.length() > 10000 )
        {
          // queue too long, combine it
          QgsGeometry tempOutputGeometry = QgsGeometry::unaryUnion( geomQueue );
          geomQueue.clear();
          geomQueue << tempOutputGeometry;
        }
      }

      feedback->setProgress( current * step );
      current++;
    }

    outputFeature.setGeometry( QgsGeometry::unaryUnion( geomQueue ) );
    sink->addFeature( outputFeature );
  }
  else
  {
    QList< int > fieldIndexes;
    Q_FOREACH ( const QString &field, fields )
    {
      int index = source->fields().lookupField( field );
      if ( index >= 0 )
        fieldIndexes << index;
    }

    QHash< QVariant, QgsAttributes > attributeHash;
    QHash< QVariant, QList< QgsGeometry > > geometryHash;

    while ( it.nextFeature( f ) )
    {
      if ( feedback->isCanceled() )
      {
        break;
      }

      if ( f.hasGeometry() && f.geometry() )
      {
        QVariantList indexAttributes;
        Q_FOREACH ( int index, fieldIndexes )
        {
          indexAttributes << f.attribute( index );
        }

        if ( !attributeHash.contains( indexAttributes ) )
        {
          // keep attributes of first feature
          attributeHash.insert( indexAttributes, f.attributes() );
        }
        geometryHash[ indexAttributes ].append( f.geometry() );
      }
Example #10
0
bool JsonParser::read( QIODevice* device )
{
    // Assert previous document got released.
    delete m_document;
    m_document = new GeoDataDocument;
    Q_ASSERT( m_document );

    // Read file data
    QJsonParseError error;
    const QJsonDocument jsonDoc = QJsonDocument::fromJson(device->readAll(), &error);

    if (jsonDoc.isNull()) {
        qDebug() << "Error parsing GeoJSON : " << error.errorString();
        return false;
    }

    // Start parsing
    const QJsonValue featuresValue = jsonDoc.object().value(QStringLiteral("features"));

    // In GeoJSON format, geometries are stored in features, so we iterate on features
    if (featuresValue.isArray()) {
        const QJsonArray featureArray = featuresValue.toArray();

        // Parse each feature
        for (int featureIndex = 0; featureIndex < featureArray.size(); ++featureIndex) {
            const QJsonObject featureObject = featureArray[featureIndex].toObject();

            // Check if the feature contains a geometry
            const QJsonValue geometryValue = featureObject.value(QStringLiteral("geometry"));
            if (geometryValue.isObject()) {
                const QJsonObject geometryObject = geometryValue.toObject();

                // Variables for creating the geometry
                QList<GeoDataGeometry*> geometryList;
                QList<GeoDataPlacemark*> placemarkList;

                // Create the different geometry types
                const QString geometryType = geometryObject.value(QStringLiteral("type")).toString().toUpper();

                if (geometryType == QLatin1String("POLYGON")) {
                    // Check first that there are coordinates
                    const QJsonValue coordinatesValue = geometryObject.value(QStringLiteral("coordinates"));
                    if (coordinatesValue.isArray()) {
                        const QJsonArray coordinateArray = coordinatesValue.toArray();

                        GeoDataPolygon * geom = new GeoDataPolygon( RespectLatitudeCircle | Tessellate );

                        // Coordinates first array will be the outer boundary, if there are more
                        // positions those will be inner holes
                        for (int ringIndex = 0 ; ringIndex < coordinateArray.size(); ++ringIndex) {
                            const QJsonArray ringArray = coordinateArray[ringIndex].toArray();

                            GeoDataLinearRing linearRing;

                            for (int coordinatePairIndex = 0; coordinatePairIndex < ringArray.size(); ++coordinatePairIndex) {
                                const QJsonArray coordinatePairArray = ringArray[coordinatePairIndex].toArray();

                                const qreal longitude = coordinatePairArray.at(0).toDouble();
                                const qreal latitude = coordinatePairArray.at(1).toDouble();

                                linearRing.append( GeoDataCoordinates( longitude , latitude , 0 , GeoDataCoordinates::Degree ) );
                            }

                            // Outer ring
                            if (ringIndex == 0) {
                                geom->setOuterBoundary( linearRing );
                            }
                            // Inner holes
                            else {
                                geom->appendInnerBoundary( linearRing );
                            }
                        }
                        geometryList.append( geom );
                    }

                } else if (geometryType == QLatin1String("MULTIPOLYGON")) {
                    // Check first that there are coordinates
                    const QJsonValue coordinatesValue = geometryObject.value(QStringLiteral("coordinates"));
                    if (coordinatesValue.isArray()) {
                        const QJsonArray coordinateArray = coordinatesValue.toArray();

                        for (int polygonIndex = 0; polygonIndex < coordinateArray.size(); ++polygonIndex) {
                            const QJsonArray polygonArray = coordinateArray[polygonIndex].toArray();

                            GeoDataPolygon * geom = new GeoDataPolygon( RespectLatitudeCircle | Tessellate );

                            // Coordinates first array will be the outer boundary, if there are more
                            // positions those will be inner holes
                            for (int ringIndex = 0 ; ringIndex < polygonArray.size(); ++ringIndex) {
                                const QJsonArray ringArray = polygonArray[ringIndex].toArray();

                                GeoDataLinearRing linearRing;

                                for (int coordinatePairIndex = 0; coordinatePairIndex < ringArray.size(); ++coordinatePairIndex) {
                                    const QJsonArray coordinatePairArray = ringArray[coordinatePairIndex].toArray();

                                    const qreal longitude = coordinatePairArray.at(0).toDouble();
                                    const qreal latitude = coordinatePairArray.at(1).toDouble();

                                    linearRing.append( GeoDataCoordinates( longitude , latitude , 0 , GeoDataCoordinates::Degree ) );
                                }

                                // Outer ring
                                if (ringIndex == 0) {
                                    geom->setOuterBoundary( linearRing );
                                }
                                // Inner holes
                                else {
                                    geom->appendInnerBoundary( linearRing );
                                }
                            }
                            geometryList.append( geom );
                        }
                    }

                } else if (geometryType == QLatin1String("LINESTRING")) {

                    // Check first that there are coordinates
                    const QJsonValue coordinatesValue = geometryObject.value(QStringLiteral("coordinates"));
                    if (coordinatesValue.isArray()) {
                        const QJsonArray coordinateArray = coordinatesValue.toArray();

                        GeoDataLineString * geom = new GeoDataLineString( RespectLatitudeCircle | Tessellate );

                        for (int coordinatePairIndex = 0; coordinatePairIndex < coordinateArray.size(); ++coordinatePairIndex) {
                            const QJsonArray coordinatePairArray = coordinateArray[coordinatePairIndex].toArray();

                            const qreal longitude = coordinatePairArray.at(0).toDouble();
                            const qreal latitude = coordinatePairArray.at(1).toDouble();

                            geom->append( GeoDataCoordinates( longitude , latitude , 0 , GeoDataCoordinates::Degree ) );
                        }
                        geometryList.append( geom );
                    }

                } else if (geometryType == QLatin1String("MULTILINESTRING")) {

                    // Check first that there are coordinates
                    const QJsonValue coordinatesValue = geometryObject.value(QStringLiteral("coordinates"));
                    if (coordinatesValue.isArray()) {
                        const QJsonArray coordinateArray = coordinatesValue.toArray();

                        for (int lineStringIndex = 0; lineStringIndex < coordinateArray.size(); ++lineStringIndex) {
                            const QJsonArray lineStringArray = coordinateArray[lineStringIndex].toArray();

                            GeoDataLineString * geom = new GeoDataLineString( RespectLatitudeCircle | Tessellate );

                            for (int coordinatePairIndex = 0; coordinatePairIndex < lineStringArray.size(); ++coordinatePairIndex) {
                                const QJsonArray coordinatePairArray = lineStringArray[coordinatePairIndex].toArray();

                                const qreal longitude = coordinatePairArray.at(0).toDouble();
                                const qreal latitude = coordinatePairArray.at(1).toDouble();

                                geom->append( GeoDataCoordinates( longitude , latitude , 0 , GeoDataCoordinates::Degree ) );
                            }
                            geometryList.append( geom );
                        }
                    }

                } else if (geometryType == QLatin1String("POINT")) {

                    // Check first that there are coordinates
                    const QJsonValue coordinatesValue = geometryObject.value(QStringLiteral("coordinates"));
                    if (coordinatesValue.isArray()) {
                        const QJsonArray coordinatePairArray = coordinatesValue.toArray();

                        GeoDataPoint * geom = new GeoDataPoint();

                        const qreal longitude = coordinatePairArray.at(0).toDouble();
                        const qreal latitude = coordinatePairArray.at(1).toDouble();

                        geom->setCoordinates( GeoDataCoordinates( longitude , latitude , 0 , GeoDataCoordinates::Degree ) );

                        geometryList.append( geom );
                    }
                } else if (geometryType == QLatin1String("MULTIPOINT")) {

                    // Check first that there are coordinates
                    const QJsonValue coordinatesValue = geometryObject.value(QStringLiteral("coordinates"));
                    if (coordinatesValue.isArray()) {
                        const QJsonArray coordinateArray = coordinatesValue.toArray();

                        for (int pointIndex = 0; pointIndex < coordinateArray.size(); ++pointIndex) {
                            const QJsonArray coordinatePairArray = coordinateArray[pointIndex].toArray();

                            GeoDataPoint * geom = new GeoDataPoint();

                            const qreal longitude = coordinatePairArray.at(0).toDouble();
                            const qreal latitude = coordinatePairArray.at(1).toDouble();

                            geom->setCoordinates( GeoDataCoordinates( longitude , latitude , 0 , GeoDataCoordinates::Degree ) );

                            geometryList.append( geom );
                        }
                    }
                }


                // Parse the features properties
                const QJsonValue propertiesValue = featureObject.value(QStringLiteral("properties"));
                if (!geometryList.isEmpty() && propertiesValue.isObject()) {
                    const QJsonObject propertiesObject = propertiesValue.toObject();

                    // First create a placemark for each geometry, there could be multi geometries
                    // that are translated into more than one geometry/placemark
                    for ( int numberGeometries = 0 ; numberGeometries < geometryList.length() ; numberGeometries++ ) {
                        GeoDataPlacemark * placemark = new GeoDataPlacemark();
                        placemarkList.append( placemark );
                    }

                    OsmPlacemarkData osmData;

                    QJsonObject::ConstIterator it = propertiesObject.begin();
                    const QJsonObject::ConstIterator end = propertiesObject.end();
                    for ( ; it != end; ++it) {
                        if (it.value().isObject() || it.value().isArray()) {
                            qDebug() << "Skipping property, values of type arrays and objects not supported:" << it.key();
                            continue;
                        }

                        // pass value through QVariant to also get bool & numbers
                        osmData.addTag(it.key(), it.value().toVariant().toString());
                    }

                    // If the property read, is the features name
                    const auto tagIter = osmData.findTag(QStringLiteral("name"));
                    if (tagIter != osmData.tagsEnd()) {
                        const QString& name = tagIter.value();
                        for (int pl = 0 ; pl < placemarkList.length(); ++pl) {
                            placemarkList.at(pl)->setName(name);
                        }
                    }

                    const GeoDataPlacemark::GeoDataVisualCategory category = StyleBuilder::determineVisualCategory(osmData);
                    if (category != GeoDataPlacemark::None) {
                        // Add the visual category to all the placemarks
                        for (int pl = 0 ; pl < placemarkList.length(); ++pl) {
                            placemarkList.at(pl)->setVisualCategory(category);
                            placemarkList.at(pl)->setOsmData(osmData);
                        }
                    }
                }

                // Add the geometry to the document
                if ( geometryList.length() == placemarkList.length() ) {

                    while( placemarkList.length() > 0 ) {

                        GeoDataPlacemark * placemark = placemarkList.last();
                        placemarkList.pop_back();

                        GeoDataGeometry * geom = geometryList.last();
                        geometryList.pop_back();

                        placemark->setGeometry( geom );
                        placemark->setVisible( true );
                        m_document->append( placemark );
                    }
                }

                // If geometries or placemarks missing inside the lists, delete them
                qDeleteAll( geometryList.begin(), geometryList.end() );
                geometryList.clear();
                qDeleteAll( placemarkList.begin(), placemarkList.end() );
                placemarkList.clear();
            }
        }
    }
    return true;
}
Example #11
0
void
AbstractTrackTableCommitter::commit( const QList<Meta::SqlTrackPtr> &tracks )
{
    // Note: The code is greatly inspired by the old ScanResultProcessor
    //  by jeffrai

    // Note2: The code is optimized for batch update.
    //  Reason: a single update is completely harmless and not frequent.
    //  The real difficulty is the collection scanner and it's runtime
    //  Especially with collections larger than 30000 tracks.

    if( tracks.isEmpty() )
        return;

    m_storage = tracks.first()->sqlCollection()->sqlStorage();

    // -- get the maximum size for our commit
    static int maxSize = 0;
    if( maxSize == 0 )
    {
        QStringList res = m_storage->query( "SHOW VARIABLES LIKE 'max_allowed_packet';" );
        if( res.size() < 2 || res[1].toInt() == 0 )
        {
            warning() << "Uh oh! For some reason MySQL thinks there isn't a max allowed size!";
            return;
        }
        debug() << "obtained max_allowed_packet is " << res[1];
        maxSize = res[1].toInt() / 3; //for safety, due to multibyte encoding
    }


    QStringList fields = getFields();

    const QString updateQueryStart = "UPDATE LOW_PRIORITY "+tableName()+" SET ";
    const QString insertQueryStart = "INSERT INTO "+tableName()+
        " ("+fields.join(",")+") VALUES ";

    QList< Meta::SqlTrackPtr > insertedTracks;
    QString insertQuery;
    insertQuery.reserve( 1024 ); // a sensible initial size

    foreach( Meta::SqlTrackPtr track, tracks )
    {
        QStringList values = getValues( track.data() );

        // -- update
        if( getId( track.data() ) > 0 )
        {
            // we just commit all values to save code complexity.
            // we would need to track the real changed fields otherwise
            QString updateQuery;
            updateQuery.reserve( 256 ); // a sensible initial size
            for( int i = 0; i < fields.count() && i < values.count(); i++ )
            {
                if( !updateQuery.isEmpty() )
                    updateQuery += ", ";
                updateQuery += fields.at( i );
                updateQuery += '=';
                updateQuery += values.at( i );
            }
            updateQuery = updateQueryStart + updateQuery +
                " WHERE id=" + QString::number( getId( track.data() ) ) + ';';
            m_storage->query( updateQuery );

        }
        else
        // -- insert
        {
            QString newValues = '(' + values.join(",") + ')';

            // - if the insertQuery is long enough, commit it.
            if( insertQueryStart.length() + insertQuery.length() + newValues.length() + 1 >= maxSize - 3 ) // ";"
            {
                // commit
                insertQuery = insertQueryStart + insertQuery + ';';
                int firstId = m_storage->insert( insertQuery, tableName() );

                // set the resulting ids
                if( firstId <= 0 )
                    warning() << "Insert failed.";
                for( int i = 0; i < insertedTracks.count(); i++ )
                    setId( const_cast<Meta::SqlTrack*>(insertedTracks.at( i ).data()),
                           firstId + i );

                insertQuery.clear();
                insertedTracks.clear();
            }

            if( !insertQuery.isEmpty() )
                insertQuery += ',';
            insertQuery += newValues;
            insertedTracks.append( track );
        }
    }
Example #12
0
void SymbolNode::getChildList( QList<Ptr>& childList ) const
{
	childList.clear();
	for (ConstChildIterator pChild = childConstBegin(); pChild != childConstEnd(); ++pChild)
		childList.push_back(pChild.value());
}
Example #13
0
unsigned char* QgsDistanceArea::measurePolygon( unsigned char* feature, double* area, double* perimeter, bool hasZptr )
{
  // get number of rings in the polygon
  unsigned int numRings = *(( int* )( feature + 1 + sizeof( int ) ) );

  if ( numRings == 0 )
    return 0;

  // Set pointer to the first ring
  unsigned char* ptr = feature + 1 + 2 * sizeof( int );

  QList<QgsPoint> points;
  QgsPoint pnt;
  double x, y;
  if ( area )
    *area = 0;
  if ( perimeter )
    *perimeter = 0;

  try
  {
    for ( unsigned int idx = 0; idx < numRings; idx++ )
    {
      int nPoints = *(( int* )ptr );
      ptr += 4;

      // Extract the points from the WKB and store in a pair of
      // vectors.
      for ( int jdx = 0; jdx < nPoints; jdx++ )
      {
        x = *(( double * ) ptr );
        ptr += sizeof( double );
        y = *(( double * ) ptr );
        ptr += sizeof( double );
        if ( hasZptr )
        {
          // totally ignore Z value
          ptr += sizeof( double );
        }

        pnt = QgsPoint( x, y );

        if ( mProjectionsEnabled && ( mEllipsoid != "NONE" ) )
        {
          pnt = mCoordTransform->transform( pnt );
        }
        points.append( pnt );
      }

      if ( points.size() > 2 )
      {
        if ( area )
        {
          double areaTmp = computePolygonArea( points );
          if ( idx == 0 )
          {
            // exterior ring
            *area += areaTmp;
          }
          else
          {
            *area -= areaTmp; // interior rings
          }
        }

        if ( perimeter )
        {
          *perimeter += measureLine( points );
        }
      }

      points.clear();

      if ( !area )
      {
        break;
      }
    }
  }
  catch ( QgsCsException &cse )
  {
    Q_UNUSED( cse );
    QgsMessageLog::logMessage( QObject::tr( "Caught a coordinate system exception while trying to transform a point. Unable to calculate polygon area or perimeter." ) );
  }

  return ptr;
}
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;
}
Example #15
0
void MainWindow::loadListFile()
{
	qDebug() << "Loading list file:" << listFile->text();

	QFile lf(listFile->text());
	if (!lf.open(QFile::ReadOnly)) {
		qWarning("Cannot open list file!");
		return;
	}
	QTextStream ts(&lf);
	ts.setCodec("UTF-8");
	if (ts.status() != QTextStream::Ok) {
		lf.close();
		qWarning("Cannot construct text stream!");
		return;
	}

	tree->clear();
	QTreeWidgetItem *item = tree->invisibleRootItem();
	while (!ts.atEnd()) {
		QString line = ts.readLine();
		if (line.isEmpty())
			continue;
		if (!filter->text().isEmpty())
			if (QRegExp(filter->text(), Qt::CaseInsensitive).indexIn(line) == -1)
				continue;
		QStringList lv = line.split('/', QString::SkipEmptyParts);
		// Extract parent path
		QList<QTreeWidgetItem *> list;
		while (item && item != tree->invisibleRootItem()) {
			list.push_front(item);
			item = item->parent();
		}
		while (!lv.isEmpty()) {
			QString str = lv.takeFirst();
			// TODO: parent folder .. support
			if (str.isEmpty() || str == ".")
				continue;
			// Remove common path from parent path
			if (!list.isEmpty()) {
				QTreeWidgetItem *it = list.takeFirst();
				if (it->text(0) == str) {
					item = it;
					continue;
				} else
					list.clear();
			}
			// Find entry
			if (!item)
				item = tree->invisibleRootItem();
			int i;
			for (i = 0; i < item->childCount(); i++)
				if (item->child(i)->text(0) == str)
					break;
			if (i == item->childCount())
				item = new QTreeWidgetItem(item, QStringList(str));
			else
				item = item->child(i);
		}
	}

	// Sort entries
	tree->sortByColumn(0, Qt::AscendingOrder);

	// Add file icons
	QFileIconProvider fip;
	QMap<QString, QIcon> iconMap;
	QTreeWidgetItemIterator it(tree->invisibleRootItem());
	while (*++it)		// Ignore root
		if ((*it)->childCount())
			(*it)->setIcon(0, fip.icon(fip.Folder));
		else {
			QFileInfo fi((*it)->text(0));
			QString sfx = fi.suffix();
#if 0	// FIXME: File icon retrieval not working
			QIcon icon = iconMap[sfx];
			if (icon.isNull()) {
				QTemporaryFile tf(QDir::tempPath() + "/XXXXXX." + sfx);
				tf.open();
				iconMap[sfx] = icon = fip.icon(fip.File/*QFileInfo(tf)*/);
			}
			(*it)->setIcon(0, icon);
#else
			iconMap[sfx] = fip.icon(fip.File);
#endif
		}

	qDebug() << "List file loaded.";
	lf.close();
}
Example #16
0
SoundGenerator::SoundGenerator(QObject *parent)
    : QObject(parent)
    , m_clockCount(0)
    , m_function(Inactive)
    , m_device(0)
    , m_timer(new QTimer(this))
{
    m_channelA.fineTune = 0;
    m_channelA.coarseTune = 0;
    m_channelA.amplitudeLevel = 0;
    m_channelA.mixValue = 0;
    m_channelA.toneOutput = 0;
    m_channelA.counter = 0;
    m_channelB.fineTune = 0;
    m_channelB.coarseTune = 0;
    m_channelB.amplitudeLevel = 0;
    m_channelB.mixValue = 0;
    m_channelB.toneOutput = 0;
    m_channelB.counter = 0;
    m_channelC.fineTune = 0;
    m_channelC.coarseTune = 0;
    m_channelC.amplitudeLevel = 0;
    m_channelC.mixValue = 0;
    m_channelC.toneOutput = 0;
    m_channelC.counter = 0;
    m_envelope.fineTune = 0;
    m_envelope.coarseTune = 0;
    m_envelope.counter = 0;
    m_envelope.shapePosition = 0;
    m_envelope.shouldHold = true;
    m_mixerA.isChannelNoiseOn = false;
    m_mixerA.isChannelToneOn = false;
    m_mixerB.isChannelNoiseOn = false;
    m_mixerB.isChannelToneOn = false;
    m_mixerC.isChannelNoiseOn = false;
    m_mixerC.isChannelToneOn = false;
    m_noise.period = 0;
    m_noise.rng = 1;
    m_noise.noiseOutput = 0xff;
    m_noise.counter = 0;

    QList<byte_t> shape;
    shape << 15 << 14 << 13 << 12 << 11 << 10 << 9 << 8 << 7 << 6 << 5 << 4 << 3 << 2 << 1 << 0;
    ENVELOPE_SHAPES.append(shape);
    ENVELOPE_SHAPES.append(shape);
    ENVELOPE_SHAPES.append(shape);
    ENVELOPE_SHAPES.append(shape);
    shape.clear();
    shape << 0 << 1 << 2 << 3 << 4 << 5 << 6 << 7 << 8 << 9 << 10 << 11 << 12 << 13 << 14 << 15 << 0;
    ENVELOPE_SHAPES.append(shape);
    ENVELOPE_SHAPES.append(shape);
    ENVELOPE_SHAPES.append(shape);
    ENVELOPE_SHAPES.append(shape);
    shape.clear();
    shape << 15 << 14 << 13 << 12 << 11 << 10 << 9 << 8 << 7 << 6 << 5 << 4 << 3 << 2 << 1 << 0;
    ENVELOPE_SHAPES.append(shape);
    ENVELOPE_SHAPES.append(shape);
    shape.clear();
    shape << 15 << 14 << 13 << 12 << 11 << 10 << 9 << 8 << 7 << 6 << 5 << 4 << 3 << 2 << 1 << 0
          << 0 << 1 << 2 << 3 << 4 << 5 << 6 << 7 << 8 << 9 << 10 << 11 << 12 << 13 << 14 << 15;
    ENVELOPE_SHAPES.append(shape);
    shape.clear();
    shape << 15 << 14 << 13 << 12 << 11 << 10 << 9 << 8 << 7 << 6 << 5 << 4 << 3 << 2 << 1 << 0 << 15;
    ENVELOPE_SHAPES.append(shape);
    shape.clear();
    shape << 0 << 1 << 2 << 3 << 4 << 5 << 6 << 7 << 8 << 9 << 10 << 11 << 12 << 13 << 14 << 15;
    ENVELOPE_SHAPES.append(shape);
    ENVELOPE_SHAPES.append(shape);
    shape.clear();
    shape << 0 << 1 << 2 << 3 << 4 << 5 << 6 << 7 << 8 << 9 << 10 << 11 << 12 << 13 << 14 << 15
          << 15 << 14 << 13 << 12 << 11 << 10 << 9 << 8 << 7 << 6 << 5 << 4 << 3 << 2 << 1 << 0;
    ENVELOPE_SHAPES.append(shape);
    shape.clear();
    shape << 0 << 1 << 2 << 3 << 4 << 5 << 6 << 7 << 8 << 9 << 10 << 11 << 12 << 13 << 14 << 15 << 0;
    ENVELOPE_SHAPES.append(shape);

    m_envelope.currentShape = ENVELOPE_SHAPES[0];

    m_audioBuffer.resize(882000);
    m_bufferPos = 0;
    m_bufferPtr = reinterpret_cast<qint8 *>(m_audioBuffer.data());

    connect(m_timer, SIGNAL(timeout()), SLOT(timerExpired()));
    m_timer->start(20);
}
/**
 * Rearranges the lines, arcs or opened polylines entities
 *  in this container, non-recoursive.
 * document can not be null
 *
 * @retval true contour are closed
 * @retval false if the contour is not closed
 *
 * @author Rallaz
 */
bool RS_ActionPolylineSegment::convertPolyline(RS_Entity* selectedEntity) {

    RS_DEBUG->print("RS_ActionPolylineSegment::convertPolyline");

    QList<RS_Entity*> remaining;
    QList<RS_Entity*> completed;
    RS_Vector start = selectedEntity->getStartpoint();
    RS_Vector end = selectedEntity->getEndpoint();
    completed.append(selectedEntity);
//get list with useful entities
    for (unsigned i=0; i<container->count(); ++i) {
        RS_Entity* e1 = container->entityAt(i);
        if (e1->isLocked() || !e1->isVisible() || e1 == selectedEntity) continue;
        if (e1->rtti()==RS2::EntityLine || e1->rtti()==RS2::EntityArc
                || e1->rtti()==RS2::EntityPolyline) {
            if (targetEntity->rtti()==RS2::EntityPolyline && ((RS_Polyline*)targetEntity)->isClosed())
                continue;
            if (e1 == selectedEntity)
                continue;
            remaining.append(e1);
        }
    }

    // find all connected entities:
    bool done = true;
    do {
        done = true;
        for (int i=(remaining.size() -1) ; i>=0; --i) {
            RS_Entity* e=remaining.at(i);
            if (e->getEndpoint().distanceTo(start) < 1.0e-4) {
                completed.prepend( e);
                start = e->getStartpoint();
                remaining.removeAt(i);
                done = false;
            } else if (e->getStartpoint().distanceTo(start) < 1.0e-4) {
                completed.prepend( e);
                start = e->getEndpoint();
                remaining.removeAt(i);
                done = false;
            } else if (e->getEndpoint().distanceTo(end) < 1.0e-4) {
                completed.append( e);
                end = e->getStartpoint();
                remaining.removeAt(i);
                done = false;
            } else if (e->getStartpoint().distanceTo(end) < 1.0e-4) {
                completed.append( e);
                end = e->getEndpoint();
                remaining.removeAt(i);
                done = false;
            }
        }
    } while (!done);

//cleanup for no more needed list
    remaining.clear();

    bool closed = false;
    if (document) {
        document->startUndoCycle();

        bool revert = false;
        double bulge = 0.0;
        if (end.distanceTo(start) < 1.0e-4)
            closed = true;

        RS_Polyline* newPolyline = new RS_Polyline(container, RS_PolylineData(RS_Vector(false), RS_Vector(false), closed));
        newPolyline->setLayerToActive();
        newPolyline->setPenToActive();

//complete polyline
        end =start;
        while (!completed.isEmpty()) {
            RS_Entity* e2= completed.takeFirst();
            e2->setUndoState(true);
            document->addUndoable(e2);
            if (e2->getStartpoint().distanceTo(end) < 1.0e-4) {
                revert = false;
                start = e2->getStartpoint();
                end = e2->getEndpoint();
            } else {
                revert = true;
                start = e2->getEndpoint();
                end = e2->getStartpoint();
            }
            if (e2->rtti()==RS2::EntityArc) {
                if (revert)
                    bulge = ((RS_Arc*)e2)->getBulge()*-1;
                else
                    bulge = ((RS_Arc*)e2)->getBulge();
            } else
                bulge = 0.0;
            if (e2->rtti()==RS2::EntityPolyline) {
                newPolyline->addVertex(start, bulge);
                end = appendPol(newPolyline, (RS_Polyline*)e2, revert);
            } else
                newPolyline->addVertex(start, bulge);
        }

        if (closed)
            newPolyline->setClosed(true);
        else
            newPolyline->addVertex(end, bulge);
        newPolyline->endPolyline();
        container->addEntity(newPolyline);

        if (graphicView) {
                graphicView->drawEntity(newPolyline);
        }

        document->addUndoable(newPolyline);
        document->endUndoCycle();
    }
    RS_DEBUG->print("RS_ActionPolylineSegment::convertPolyline: OK");
    return closed;
}
Example #18
0
void OscilloscopeEngine::processOscilloscopeData(SamplesList leftChannelData, SamplesList rightChannelData)
{
    if (!m_isRunning) {
        return;
    }
//    qDebug() << "Got" << samples.length() << "samples";
    if (m_capturedChannels == CHANNEL_NONE) {
        return;
    }
    SamplesList *buffer = NULL;
    SamplesList *samples = NULL;
    // I.   Select primary channel
    if (m_capturedChannels != CHANNEL_BOTH) {
        // For single channel capture, process only one buffer.
        if (m_capturedChannels == CHANNEL_LEFT) {
            buffer = &m_samplesInputBufferLeft;
            samples = &leftChannelData;
        } else if (m_capturedChannels == CHANNEL_RIGHT) {
            buffer = &m_samplesInputBufferRight;
            samples = &rightChannelData;
        }
    } else {
        // For both channel capture, only one channel is selected for Normal or Single triggering
        if (m_triggerChannel == CHANNEL_LEFT) {
            buffer = &m_samplesInputBufferLeft;
        } else if (m_triggerChannel == CHANNEL_RIGHT) {
            buffer = &m_samplesInputBufferRight;
        } else if (m_triggerMode != TRIG_AUTO) {
            qWarning() << "For non-auto trigger mode an one channel have to be choosen for triggering";
            Q_ASSERT(false);
            return;
        }
    }
    // II.  For both channel capture we have to check buffers state - samples must be captured simultaneously
    if (m_capturedChannels == CHANNEL_BOTH) {
        // This is not a bug when
        if (m_samplesInputBufferLeft.size() != m_samplesInputBufferRight.size()) {
            qWarning() << "Audio input buffers are not synced. Reset them."
                       << "Left:" << m_samplesInputBufferLeft.size()
                       << "Right:" << m_samplesInputBufferRight.size();
            m_samplesInputBufferLeft.clear();
            m_samplesInputBufferRight.clear();
//            Q_ASSERT(false);
        }
        if (leftChannelData.size() != rightChannelData.size()) {
            qWarning() << "Fresh audio samples are not synced. Reset them."
                       << "Left:" << leftChannelData.size()
                       << "Right:" << rightChannelData.size();
            leftChannelData.clear();
            rightChannelData.clear();
//            Q_ASSERT(false);
        }
    }
    // III. Trigger mode: Automatic - display data immediatelly if there are enough data in buffer
    if (m_triggerMode == TRIG_AUTO) {
        if (m_capturedChannels != CHANNEL_BOTH) {
            buffer->append(*samples);
            if (buffer->size() < m_frameLength) {
                return;
            }
        } else {
            m_samplesInputBufferLeft.append(leftChannelData);
            m_samplesInputBufferRight.append(rightChannelData);
            if (m_samplesInputBufferLeft.size() < m_frameLength) {
                return;
            }
        }
        displayOscilloscopeChannelData(0, m_frameLength, m_frameLength);
        return;
    }
    // IV.  Trigger mode: Single - if data acqured, the graph have to hold data
    if ((m_triggerMode == TRIG_SINGLE) && m_dataForSingleCaptureAcqured) {
        return;
    }
    // V.   Trigger mode: Normal or Single (when trigger hasn't fired yet)
    if ((m_triggerMode == TRIG_NORMAL) or (m_triggerMode == TRIG_SINGLE)) {
        // Fill buffers with samples
        if (m_capturedChannels != CHANNEL_BOTH) {
            buffer->append(*samples);
            if (buffer->size() < m_frameLength * 2) {
                return;
            }
        } else {
            m_samplesInputBufferLeft.append(leftChannelData);
            m_samplesInputBufferRight.append(rightChannelData);
            if (m_samplesInputBufferLeft.size() < m_frameLength * 2) {
                return;
            }
        }
        // Find moments when signal intersects trigger line by required slope
        // Start searching with offset in half of frame length, because this half has been already plotted
        QList<int> eventsOffsets;
        for (int offset = m_frameLength / 2 - 1;  offset < buffer->size(); ++offset) {
            qreal cur = buffer->at(offset);
            qreal prev = buffer->at(offset - 1);
            if (m_triggerSlope == TRIG_RISING) {
                if ((prev <= m_triggerLevel) && (cur >= m_triggerLevel)) {
                    eventsOffsets.append(offset);
                }
            } else {
                if ((prev >= m_triggerLevel) && (cur <= m_triggerLevel)) {
                    eventsOffsets.append(offset);
                }
            }
        }
        if (eventsOffsets.size() > 0) {
            // take first event in next frame
            for (int i = 0; i < eventsOffsets.size(); ++i) {
                int offset = eventsOffsets[i];
                if (offset >= m_frameLength * 3 / 2) {
                    // there is not enough data for display full frame
                    eventsOffsets.clear();
                    break;
                }
                if (offset >= m_frameLength / 2) {
                    displayOscilloscopeChannelData(offset - m_frameLength / 2, m_frameLength, m_frameLength / 2);
                    m_dataForSingleCaptureAcqured = true;
                    return;
                }
            }
            // or select last event
            if (eventsOffsets.size() > 0) {
                int offset = eventsOffsets.last();
                displayOscilloscopeChannelData(offset - m_frameLength / 2, m_frameLength, m_frameLength / 2);
                m_dataForSingleCaptureAcqured = true;
                return;
            }
        }
        // buffer is overflowed
        if (buffer->size() > m_frameLength * 2) {
            if (m_capturedChannels != CHANNEL_BOTH) {
                *buffer = buffer->mid(m_frameLength);
            } else {
                m_samplesInputBufferLeft = m_samplesInputBufferLeft.mid(m_frameLength);
                m_samplesInputBufferRight = m_samplesInputBufferRight.mid(m_frameLength);
            }
        }
    }
}
Example #19
0
int QgsMapCanvasSnapper::snapToBackgroundLayers( const QgsPoint& point, QList<QgsSnappingResult>& results, const QList<QgsPoint>& excludePoints )
{
  results.clear();

  if ( !mSnapper )
    return 5;

  //topological editing on?
  int topologicalEditing = QgsProject::instance()->readNumEntry( "Digitizing", "/TopologicalEditing", 0 );

  //snapping on intersection on?
  int intersectionSnapping = QgsProject::instance()->readNumEntry( "Digitizing", "/IntersectionSnapping", 0 );

  if ( topologicalEditing == 0 )
  {
    if ( intersectionSnapping == 0 )
      mSnapper->setSnapMode( QgsSnapper::SnapWithOneResult );
    else
      mSnapper->setSnapMode( QgsSnapper::SnapWithResultsWithinTolerances );
  }
  else if ( intersectionSnapping == 0 )
  {
    mSnapper->setSnapMode( QgsSnapper::SnapWithResultsForSamePosition );
  }
  else
  {
    mSnapper->setSnapMode( QgsSnapper::SnapWithResultsWithinTolerances );
  }

  QgsVectorLayer* currentVectorLayer = dynamic_cast<QgsVectorLayer*>( mMapCanvas->currentLayer() );
  if ( !currentVectorLayer )
  {
    return 1;
  }

  //read snapping settings from project
  QStringList layerIdList, enabledList, toleranceList, toleranceUnitList, snapToList;

  bool ok, snappingDefinedInProject;

  QSettings settings;
  QString snappingMode = QgsProject::instance()->readEntry( "Digitizing", "/SnappingMode", "current_layer", &snappingDefinedInProject );
  QString defaultSnapToleranceUnit = snappingDefinedInProject ? QgsProject::instance()->readEntry( "Digitizing", "/DefaultSnapToleranceUnit" ) : settings.value( "/qgis/digitizing/default_snapping_tolerance_unit", "0" ).toString();
  QString defaultSnapType = snappingDefinedInProject ? QgsProject::instance()->readEntry( "Digitizing", "/DefaultSnapType" ) : settings.value( "/qgis/digitizing/default_snap_mode", "off" ).toString();
  QString defaultSnapTolerance = snappingDefinedInProject ? QString::number( QgsProject::instance()->readDoubleEntry( "Digitizing", "/DefaultSnapTolerance" ) ) : settings.value( "/qgis/digitizing/default_snapping_tolerance", "0" ).toString();

  if ( !snappingDefinedInProject && defaultSnapType == "off" )
  {
    return 0;
  }

  if ( snappingMode == "current_layer" || !snappingDefinedInProject )
  {
    layerIdList.append( currentVectorLayer->id() );
    enabledList.append( "enabled" );
    toleranceList.append( defaultSnapTolerance );
    toleranceUnitList.append( defaultSnapToleranceUnit );
    snapToList.append( defaultSnapType );
  }
  else if ( snappingMode == "all_layers" )
  {
    QList<QgsMapLayer*> allLayers = mMapCanvas->layers();
    QList<QgsMapLayer*>::const_iterator layerIt = allLayers.constBegin();
    for ( ; layerIt != allLayers.constEnd(); ++layerIt )
    {
      if ( !( *layerIt ) )
      {
        continue;
      }
      layerIdList.append(( *layerIt )->id() );
      enabledList.append( "enabled" );
      toleranceList.append( defaultSnapTolerance );
      toleranceUnitList.append( defaultSnapToleranceUnit );
      snapToList.append( defaultSnapType );
    }
  }
  else //advanced
  {
    layerIdList = QgsProject::instance()->readListEntry( "Digitizing", "/LayerSnappingList", QStringList(), &ok );
    enabledList = QgsProject::instance()->readListEntry( "Digitizing", "/LayerSnappingEnabledList", QStringList(), &ok );
    toleranceList = QgsProject::instance()->readListEntry( "Digitizing", "/LayerSnappingToleranceList", QStringList(), &ok );
    toleranceUnitList = QgsProject::instance()->readListEntry( "Digitizing", "/LayerSnappingToleranceUnitList", QStringList(), &ok );
    snapToList = QgsProject::instance()->readListEntry( "Digitizing", "/LayerSnapToList", QStringList(), &ok );
  }

  if ( !( layerIdList.size() == enabledList.size() &&
          layerIdList.size() == toleranceList.size() &&
          layerIdList.size() == toleranceUnitList.size() &&
          layerIdList.size() == snapToList.size() ) )
  {
    // lists must have the same size, otherwise something is wrong
    return 1;
  }

  QList<QgsSnapper::SnapLayer> snapLayers;
  QgsSnapper::SnapLayer snapLayer;



  // set layers, tolerances, snap to segment/vertex to QgsSnapper
  QStringList::const_iterator layerIt( layerIdList.constBegin() );
  QStringList::const_iterator tolIt( toleranceList.constBegin() );
  QStringList::const_iterator tolUnitIt( toleranceUnitList.constBegin() );
  QStringList::const_iterator snapIt( snapToList.constBegin() );
  QStringList::const_iterator enabledIt( enabledList.constBegin() );
  for ( ; layerIt != layerIdList.constEnd(); ++layerIt, ++tolIt, ++tolUnitIt, ++snapIt, ++enabledIt )
  {
    if ( *enabledIt != "enabled" )
    {
      // skip layer if snapping is not enabled
      continue;
    }

    //layer
    QgsVectorLayer *vlayer = qobject_cast<QgsVectorLayer *>( QgsMapLayerRegistry::instance()->mapLayer( *layerIt ) );
    if ( !vlayer || !vlayer->hasGeometryType() )
      continue;

    snapLayer.mLayer = vlayer;

    //tolerance
    snapLayer.mTolerance = tolIt->toDouble();
    snapLayer.mUnitType = ( QgsTolerance::UnitType ) tolUnitIt->toInt();

    // segment or vertex
    if ( *snapIt == "to vertex" || *snapIt == "to_vertex" )
    {
      snapLayer.mSnapTo = QgsSnapper::SnapToVertex;
    }
    else if ( *snapIt == "to segment" || *snapIt == "to_segment" )
    {
      snapLayer.mSnapTo = QgsSnapper::SnapToSegment;
    }
    else if ( *snapIt == "to vertex and segment" || *snapIt == "to_vertex_and_segment" )
    {
      snapLayer.mSnapTo = QgsSnapper::SnapToVertexAndSegment;
    }
    else //off
    {
      continue;
    }

    snapLayers.append( snapLayer );
  }

  mSnapper->setSnapLayers( snapLayers );

  if ( mSnapper->snapMapPoint( point, results, excludePoints ) != 0 )
    return 4;

  if ( intersectionSnapping != 1 )
    return 0;

  QVector<QgsSnappingResult> segments;
  QVector<QgsSnappingResult> points;
  for ( QList<QgsSnappingResult>::const_iterator it = results.constBegin();
        it != results.constEnd();
        ++it )
  {
    if ( it->snappedVertexNr == -1 )
    {
      QgsDebugMsg( "segment" );
      segments.push_back( *it );
    }
    else
    {
      QgsDebugMsg( "no segment" );
      points.push_back( *it );
    }
  }

  if ( segments.count() < 2 )
    return 0;

  QList<QgsSnappingResult> myResults;

  for ( QVector<QgsSnappingResult>::const_iterator oSegIt = segments.constBegin();
        oSegIt != segments.constEnd();
        ++oSegIt )
  {
    QgsDebugMsg( QString::number( oSegIt->beforeVertexNr ) );

    QVector<QgsPoint> vertexPoints;
    vertexPoints.append( oSegIt->beforeVertex );
    vertexPoints.append( oSegIt->afterVertex );

    QgsGeometry* lineA = QgsGeometry::fromPolyline( vertexPoints );

    for ( QVector<QgsSnappingResult>::iterator iSegIt = segments.begin();
          iSegIt != segments.end();
          ++iSegIt )
    {
      QVector<QgsPoint> vertexPoints;
      vertexPoints.append( iSegIt->beforeVertex );
      vertexPoints.append( iSegIt->afterVertex );

      QgsGeometry* lineB = QgsGeometry::fromPolyline( vertexPoints );
      QgsGeometry* intersectionPoint = lineA->intersection( lineB );
      delete lineB;

      if ( intersectionPoint && intersectionPoint->type() == QGis::Point )
      {
        //We have to check the intersection point is inside the tolerance distance for both layers
        double toleranceA = 0;
        double toleranceB = 0;
        for ( int i = 0 ;i < snapLayers.size();++i )
        {
          if ( snapLayers[i].mLayer == oSegIt->layer )
          {
            toleranceA = QgsTolerance::toleranceInMapUnits( snapLayers[i].mTolerance, snapLayers[i].mLayer, mMapCanvas->mapSettings(), snapLayers[i].mUnitType );
          }
          if ( snapLayers[i].mLayer == iSegIt->layer )
          {
            toleranceB = QgsTolerance::toleranceInMapUnits( snapLayers[i].mTolerance, snapLayers[i].mLayer, mMapCanvas->mapSettings(), snapLayers[i].mUnitType );
          }
        }
        QgsGeometry* cursorPoint = QgsGeometry::fromPoint( point );
        double distance = intersectionPoint->distance( *cursorPoint );
        if ( distance < toleranceA && distance < toleranceB )
        {
          iSegIt->snappedVertex = intersectionPoint->asPoint();
          myResults.append( *iSegIt );
        }
        delete cursorPoint;
      }
      delete intersectionPoint;

    }

    delete lineA;
  }

  if ( myResults.length() > 0 )
  {
    results.clear();
    results = myResults;
  }

  return 0;
}
bool QgsNativeMetadataValidator::validate( const QgsLayerMetadata &metadata, QList<ValidationResult> &results ) const
{
  results.clear();

  bool result = true;
  if ( metadata.identifier().isEmpty() )
  {
    result = false;
    results << ValidationResult( QObject::tr( "identifier" ), QObject::tr( "Identifier element is required." ) );
  }

  if ( metadata.language().isEmpty() )
  {
    result = false;
    results << ValidationResult( QObject::tr( "language" ), QObject::tr( "Language element is required." ) );
  }

  if ( metadata.type().isEmpty() )
  {
    result = false;
    results << ValidationResult( QObject::tr( "type" ), QObject::tr( "Type element is required." ) );
  }

  if ( metadata.title().isEmpty() )
  {
    result = false;
    results << ValidationResult( QObject::tr( "title" ), QObject::tr( "Title element is required." ) );
  }

  if ( metadata.abstract().isEmpty() )
  {
    result = false;
    results << ValidationResult( QObject::tr( "abstract" ), QObject::tr( "Abstract element is required." ) );
  }

  if ( metadata.licenses().isEmpty() )
  {
    result = false;
    results << ValidationResult( QObject::tr( "license" ), QObject::tr( "At least one license is required." ) );
  }

  if ( !metadata.crs().isValid() )
  {
    result = false;
    results << ValidationResult( QObject::tr( "crs" ), QObject::tr( "A valid CRS element is required." ) );
  }

  int index = 0;
  Q_FOREACH ( const QgsLayerMetadata::SpatialExtent &extent, metadata.extent().spatialExtents() )
  {
    if ( !extent.extentCrs.isValid() )
    {
      result = false;
      results << ValidationResult( QObject::tr( "extent" ), QObject::tr( "A valid CRS element for the spatial extent is required." ), index );
    }

    if ( extent.bounds.width() == 0.0 || extent.bounds.height() == 0.0 )
    {
      result = false;
      results << ValidationResult( QObject::tr( "extent" ), QObject::tr( "A valid spatial extent is required." ), index );
    }
    index++;
  }

  if ( metadata.contacts().isEmpty() )
  {
    result = false;
    results << ValidationResult( QObject::tr( "contacts" ), QObject::tr( "At least one contact is required." ) );
  }

  if ( metadata.links().isEmpty() )
  {
    result = false;
    results << ValidationResult( QObject::tr( "links" ), QObject::tr( "At least one link is required." ) );
  }

  // validate keywords
  QgsLayerMetadata::KeywordMap keywords = metadata.keywords();
  QgsLayerMetadata::KeywordMap::const_iterator keywordIt = keywords.constBegin();
  index = 0;
  for ( ; keywordIt != keywords.constEnd(); ++keywordIt )
  {
    if ( keywordIt.key().isEmpty() )
    {
      result = false;
      results << ValidationResult( QObject::tr( "keywords" ), QObject::tr( "Keyword vocabulary cannot be empty." ), index );
    }
    if ( keywordIt.value().isEmpty() )
    {
      result = false;
      results << ValidationResult( QObject::tr( "keywords" ), QObject::tr( "Keyword list cannot be empty." ), index );
    }
    index++;
  }

  // validate contacts
  index = 0;
  Q_FOREACH ( const QgsLayerMetadata::Contact &contact, metadata.contacts() )
  {
    if ( contact.name.isEmpty() )
    {
      result = false;
      results << ValidationResult( QObject::tr( "contacts" ), QObject::tr( "Contact name cannot be empty." ), index );
    }
    index++;
  }

  // validate links
  index = 0;
  Q_FOREACH ( const QgsLayerMetadata::Link &link, metadata.links() )
  {
    if ( link.name.isEmpty() )
    {
      result = false;
      results << ValidationResult( QObject::tr( "links" ), QObject::tr( "Link name cannot be empty." ), index );
    }
    if ( link.type.isEmpty() )
    {
      result = false;
      results << ValidationResult( QObject::tr( "links" ), QObject::tr( "Link type cannot be empty." ), index );
    }
    if ( link.url.isEmpty() )
    {
      result = false;
      results << ValidationResult( QObject::tr( "links" ), QObject::tr( "Link url cannot be empty." ), index );
    }
    index++;
  }

  return result;
}
Example #21
0
void TexecutorSupply::createQuestionsList(QList<TQAgroup> &list) {
	char openStr[6];
//       for (int i = 0; i < 6; i++)
	for (int i = 0; i < Tcore::gl()->Gtune()->stringNr(); i++)
			openStr[i] = Tcore::gl()->Gtune()->str(i + 1).chromatic();
		
		/** FIXING MISTAKE RELATED WITH A NEW VALIDATION WAY DURING SAVING NEW LEVEL 
			* When there is no guitar in a level,
			* add to question list only the lowest position sounds. 
			* In this way question list contains proper number of questions. */
	if (!m_level->canBeGuitar() && !m_level->answerIsSound())  // adjust fret range
		m_level->onlyLowPos = true;

	if (!m_playCorrections || m_level->instrument != e_noInstrument || m_level->showStrNr || m_level->canBeGuitar()) {
// 		qDebug() << "Question list created fret by fret. Tune:" << Tcore::gl()->Gtune()->name << Tcore::gl()->Gtune()->stringNr();
		if (m_level->instrument == e_noInstrument && Tcore::gl()->instrument != e_noInstrument) {
// 			if (Tnote(Tcore::gl()->hiString().chromatic() + m_hiFret).chromatic() < m_level->hiNote.chromatic())
// 					m_hiFret = m_level->hiNote.chromatic() - Tcore::gl()->hiString().chromatic();
// 			if (Tnote(Tcore::gl()->loString().chromatic() + m_loFret).chromatic() > m_level->loNote.chromatic())
// 				m_loFret = Tcore::gl()->loString().chromatic() - m_level->loNote.chromatic();
			char hi = m_hiFret, lo = m_loFret;
			if (!m_level->adjustFretsToScale(lo, hi))
					qDebug() << "Cant adjust fret range. Corrections will be played!";
			m_loFret = lo; 
			m_hiFret = hi;
		}
		if (m_level->loFret != m_loFret || m_level->hiFret != m_hiFret)
				qDebug() << "Fret range of a level adjusted to current instrument [" << m_loFret << m_hiFret << "]";
		for(int s = 0; s < Tcore::gl()->Gtune()->stringNr(); s++) {
				if (m_level->usedStrings[Tcore::gl()->strOrder(s)])// check string by strOrder
						for (int f = m_loFret; f <= m_hiFret; f++) {
								Tnote n = Tnote(Tcore::gl()->Gtune()->str(Tcore::gl()->strOrder(s) + 1).chromatic() + f);
							if (n.chromatic() >= m_level->loNote.chromatic() &&
										n.chromatic() <= m_level->hiNote.chromatic()) {
								bool hope = true; // we still have hope that note is proper for the level
								if (m_level->onlyLowPos) {
									if (s > 0) {
											// we have to check when note is on the lowest positions.
											// Is it really lowest position when strOrder[s] is 0 - it is the highest sting
											char diff = openStr[Tcore::gl()->strOrder(s-1)] - openStr[Tcore::gl()->strOrder(s)];
											if( (f - diff) >= m_loFret && (f - diff) <= m_hiFret)
													hope = false; //There is the same note on highest string
											else
													hope = true;
									}
								}
								if (hope && m_level->useKeySign && m_level->onlyCurrKey)
									hope = isNoteInKey(n);
								if (hope) {
										if (n.alter && (!m_level->withFlats && !m_level->withSharps))
												continue;
										else {
											TfingerPos ff = TfingerPos(Tcore::gl()->strOrder(s) + 1, f);
											addToList(list, n, ff);
										}
								}
						}
				}
		}
	} else {
// 		qDebug() << "Question list created note by note";
		for (int nNr = m_level->loNote.chromatic(); nNr <= m_level->hiNote.chromatic(); nNr++) {
			Tnote n = Tnote(nNr);
			bool hope = true; // we still have hope that note is proper for the level
			if (hope && m_level->useKeySign && m_level->onlyCurrKey)
					hope = isNoteInKey(n);
			if (hope) {
				if (n.alter && (!m_level->withFlats && !m_level->withSharps))
						continue;
				else {
						TfingerPos ff = TfingerPos();
						addToList(list, n, ff);
				}
		}
		}
	}	
	
//    for (int i = 0; i < list.size(); i++)
//        qDebug() << i << (int)list[i].pos.str() << "f"
//                << (int)list[i].pos.fret() << " note: "
//                << QString::fromStdString(list[i].note.getName());

  // generate m_fretFretList if needed
    m_fretFretList.clear();
    if (m_level->questionAs.isFret() && m_level->answersAs[TQAtype::e_asFretPos].isFret()) {
      QList<TfingerPos> tmpSameList;
      for (int i = 0; i < list.size(); i++) {
        tmpSameList.clear();
        getTheSamePos(list[i].pos, tmpSameList);
          if (!tmpSameList.isEmpty())
            m_fretFretList << (quint16)i;
      }
//       for (int i = 0; i < m_fretFretList.size(); i++)
//        qDebug() << m_fretFretList.at(i) << (int)list[m_fretFretList.at(i)].pos.str() << "f"
//                << (int)list[m_fretFretList.at(i)].pos.fret() << " note: "
//                << QString::fromStdString(list[m_fretFretList.at(i)].note.getName());
//       qDebug() << "question list for only guitar created\nnumber:" << m_fretFretList.size() <<
//           " among:" << list.size();
    }
    
    qsrand(QDateTime::currentDateTime().toTime_t());
    
		if (m_level->canBeMelody())
			m_obligQuestNr = qBound(5, 250 / m_level->melodyLen, 30); // longer melody - less questions
		else
			m_obligQuestNr = qBound(20, list.size() * 4, 250);
    if (m_level->useKeySign && !m_level->isSingleKey)
        m_obligQuestNr = qMax(m_obligQuestNr, (m_level->hiKey.value() - m_level->loKey.value() + 1) * 5);
    m_obligQuestNr = qMax(qaPossibilities() * 4, m_obligQuestNr);
}
Example #22
0
void WiresharkApplication::clearRecentItems() {
    qDeleteAll(recent_items_.begin(), recent_items_.end());
    recent_items_.clear();
    emit updateRecentItemStatus(NULL, 0, false);
}
Example #23
0
void MainScreen::doSend()
{
	QList<int> order = randomizeBuyers();
	//QList<Participant> receivers(m_participants.size());

	typedef QPair<Participant, Participant> ParticipantPair;
	QList<ParticipantPair> pairs;

	bool success = false;
	while(!success)
	{
	  bool errorOccurred = false;
	  for(int i = 0; !errorOccurred && i < m_participants.size(); ++i)
	  {
	          // refactor the drafting out into it's own class.  The Input reader
	          // should not know about how drafting occurs
		  	  int j = order[i];

	          Participant buyer(m_participants.value(j)["name"].value<QString>(), m_participants.value(j)["email"].value<QString>(), m_participants.value(j)["exl"].value<QStringList>());
	          Participant receiver(m_participants.value(i)["name"].value<QString>(), m_participants.value(i)["email"].value<QString>(), m_participants.value(i)["exl"].value<QStringList>());
	          if(!IsValidPair(buyer, receiver))
	          {
	            errorOccurred = true;
	          }
	          else
	          {
	        	  pairs.append(ParticipantPair(buyer,receiver));
	          }
	  }

	  if(errorOccurred)
	  {

		  order = randomizeBuyers();
			pairs.clear();
	  }
	  else
	  {
		success = true;
	  }
	}

	AccountService* as = new AccountService();
	Account account = as->defaultAccount(Service::Messages);

	MessageService ms;
	m_subject = m_mainPage->findChild<TextField*>("emailSubject")->text();
	QString body = "<p>" + m_mainPage->findChild<TextArea*>("emailBody")->text() + "</p>";

	for(int i = 0; i < pairs.size(); ++i)
	{
	  QString greeting = "<p>Hi " + pairs[i].first.getName() + "!</p>";
	  QString youGot = "You Received: " + pairs[i].second.getName();
		MessageBuilder* builder = MessageBuilder::create(account.id());
		MessageContact rto = MessageContact(-1,MessageContact::To,pairs[i].first.getName(), pairs[i].first.getEmail());
		QString fullMsg = greeting + body + youGot;
		QByteArray bodyData = fullMsg.toAscii();
		builder->subject(m_subject);
		bool added;
		builder->addRecipient(rto,&added);
		builder->body(MessageBody::Html,bodyData);
		Message message = *builder;

/*
	    connect(&m_messageService, SIGNAL( messageUpdated(bb::pim::account::AccountKey, bb::pim::message::ConversationKey, bb::pim::message::MessageKey, bb::pim::message::MessageUpdate) ),
	            &m_ml,
	            SLOT( messageUpdate(bb::pim::account::AccountKey, bb::pim::message::ConversationKey, bb::pim::message::MessageKey, bb::pim::message::MessageUpdate) ) );
*/


		/*MessageKey mk = */ms.send(account.id(), message);
		/*Message sentMessage = ms.message(account.id(), mk);
		m_ml.setAk(account.id());
		m_ml.setMk(sentMessage.id());
		m_ml.setCk(sentMessage.conversationId());
		m_ml.setMsg(sentMessage);*/
		//********************************************************
	    // Set created root object as the application scene
	    //m_navPane->setBackButtonsVisible(false);
	}

	m_worker->exit();

}
ConfigureEvent_EnableDisableObject::ConfigureEvent_EnableDisableObject(int menuID, int menuType, QWidget *parent) : QDialog(parent)
{
	QList<MenuObject*> menuObjects;
	QStringList objectNames;
	StorageFile storageFile;
	QString storageLocation;
	setupUi(this);
	if (menuType == MenuObject::MENUTYPE_MAINMENU)
	{
		ProjectData::DataReference<MainMenuLayout> *layoutRef = new ProjectData::DataReference<MainMenuLayout>(menuID, __FILE__, __LINE__);
		menuObjects = (*layoutRef)->getObjectsByType(MenuObject::TYPE_FRAME);
		menuObjects += (*layoutRef)->getObjectsByType(MenuObject::TYPE_TEXT);
		menuObjects += (*layoutRef)->getObjectsByType(MenuObject::TYPE_IMAGE);
		menuObjects += (*layoutRef)->getObjectsByType(MenuObject::TYPE_SELECTABLEAREA);
		menuObjects += (*layoutRef)->getObjectsByType(MenuObject::TYPE_SCROLLAREA);
		menuObjects += (*layoutRef)->getObjectsByType(MenuObject::TYPE_ITEMLIST);
		for (int i = 0; i < menuObjects.size(); ++i)
			objectNames.append(menuObjects[i]->getName());
		objectNames.sort();
		cboxMenuObject->addItems(objectNames);
		menuObjects.clear();
		delete layoutRef;
	}
	else if (menuType == MenuObject::MENUTYPE_POPUPMENU)
	{
		ProjectData::DataReference<PopupMenuLayout> *layoutRef = new ProjectData::DataReference<PopupMenuLayout>(menuID, __FILE__, __LINE__);
		menuObjects = (*layoutRef)->getObjectsByType(MenuObject::TYPE_FRAME);
		menuObjects += (*layoutRef)->getObjectsByType(MenuObject::TYPE_TEXT);
		menuObjects += (*layoutRef)->getObjectsByType(MenuObject::TYPE_IMAGE);
		menuObjects += (*layoutRef)->getObjectsByType(MenuObject::TYPE_SELECTABLEAREA);
		menuObjects += (*layoutRef)->getObjectsByType(MenuObject::TYPE_SCROLLAREA);
		menuObjects += (*layoutRef)->getObjectsByType(MenuObject::TYPE_ITEMLIST);
		for (int i = 0; i < menuObjects.size(); ++i)
			objectNames.append(menuObjects[i]->getName());
		objectNames.sort();
		cboxMenuObject->addItems(objectNames);
		menuObjects.clear();
		delete layoutRef;
	}
	else if (menuType == MenuObject::MENUTYPE_TITLESCREENMENU)
	{
		TitleMenuLayout *layout = ProjectData::titleMenuLayout;
		menuObjects = layout->getObjectsByType(MenuObject::TYPE_FRAME);
		menuObjects += layout->getObjectsByType(MenuObject::TYPE_TEXT);
		menuObjects += layout->getObjectsByType(MenuObject::TYPE_IMAGE);
		menuObjects += layout->getObjectsByType(MenuObject::TYPE_SELECTABLEAREA);
		menuObjects += layout->getObjectsByType(MenuObject::TYPE_SCROLLAREA);
		menuObjects += layout->getObjectsByType(MenuObject::TYPE_ITEMLIST);
		for (int i = 0; i < menuObjects.size(); ++i)
			objectNames.append(menuObjects[i]->getName());
		objectNames.sort();
		cboxMenuObject->addItems(objectNames);
		menuObjects.clear();
		layout = NULL;
	}
	if (cboxMenuObject->count() == 0)
	{
		cboxMenuObject->addItem("No Selectable Areas or Item Lists To Select");
		buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);
	}
	resize(sizeHint().width(), sizeHint().height());
	setMinimumWidth(width());
	setMaximumWidth(width());
	setMinimumHeight(height());
	setMaximumHeight(height());
}
Example #25
0
//
// Slot to update the configuration then exit.  Called when  ui.pushButton_ok
// is clicked. Step through each page of the QToolBox and send any entries
// to connman.
void PropertiesEditor::updateConfiguration()
{
  // Some variables
  QString s;
  QStringList sl;
  QList<QVariant> vlist;
  QMap<QString,QVariant> dict;
  QDBusInterface* iface_serv = new QDBusInterface(DBUS_SERVICE, objpath.path(), "net.connman.Service", QDBusConnection::systemBus(), this);
  QList<QLineEdit*> lep;
  QStringList slp;

  // QCheckboxes
  // Only update if changed
  if (ui.checkBox_autoconnect->isChecked() != objmap.value("AutoConnect").toBool() ) {
    vlist.clear();
    vlist << "AutoConnect";
    vlist << QVariant::fromValue(QDBusVariant(ui.checkBox_autoconnect->isChecked()) );
    shared::processReply(iface_serv->callWithArgumentList(QDBus::AutoDetect, "SetProperty", vlist) );
  }

  // QLineEdits (nameservers, timeservers and domains)
  lep.clear();
  slp.clear();
  lep << ui.lineEdit_nameservers << ui.lineEdit_timeservers << ui.lineEdit_domains;
  slp << "Nameservers.Configuration" << "Timeservers.Configuration" << "Domains.Configuration";
  for (int i = 0; i < lep.count(); ++i) {
    s = lep.at(i)->text();
    s.replace(',', ' ');
    s.replace(';', ' ');
    s = s.simplified();

    if (s.isEmpty() ) sl.clear();
    else sl = s.split(' ');

    // Only update if an entry has changed.
    if (sl != objmap.value(slp.at(i)).toStringList()) {
      vlist.clear();
      vlist << slp.at(i);
      vlist << QVariant::fromValue(QDBusVariant(sl) );
      shared::processReply(iface_serv->callWithArgumentList(QDBus::AutoDetect, "SetProperty", vlist) );
    } // if
  } //for

  // ipv4
  // Only update if an entry has changed.
  if ((ui.comboBox_ipv4method->currentText() != TranslateStrings::cmtr(ipv4map.value("Method").toString()) )	|
      (ui.lineEdit_ipv4address->text() != TranslateStrings::cmtr(ipv4map.value("Address").toString()) )      	|
      (ui.lineEdit_ipv4netmask->text() != TranslateStrings::cmtr(ipv4map.value("Netmask").toString()) )				|
      (ui.lineEdit_ipv4gateway->text() != TranslateStrings::cmtr(ipv4map.value("Gateway").toString())) )			{

    vlist.clear();
    lep.clear();
    slp.clear();
    dict.clear();
    vlist << "IPv4.Configuration";
    dict.insert("Method", sl_ipv4_method.at(ui.comboBox_ipv4method->currentIndex()) );

    lep << ui.lineEdit_ipv4address << ui.lineEdit_ipv4netmask << ui.lineEdit_ipv4gateway;
    slp << "Address" << "Netmask" << "Gateway";
    for (int i = 0; i < lep.count(); ++i) {
      s = lep.at(i)->text();
      s = s.simplified(); // really should not be needed with the validator
      if (s.isEmpty() ) s.clear();
      dict.insert(slp.at(i), s);
    } // for

    vlist << QVariant::fromValue(QDBusVariant(dict) );
    shared::processReply(iface_serv->callWithArgumentList(QDBus::AutoDetect, "SetProperty", vlist) );
  } // if ipv4 changed

  // ipv6
  // Only update if an entry has changed.
  if ((ui.comboBox_ipv6method->currentText() != TranslateStrings::cmtr(ipv6map.value("Method").toString()) ) 		|
      (static_cast<uint>(ui.spinBox_ipv6prefixlength->value()) != ipv6map.value("PrefixLength").toUInt() )    	|
      (ui.lineEdit_ipv6address->text() != TranslateStrings::cmtr(ipv6map.value("Address").toString()) )    	    |
      (ui.lineEdit_ipv6gateway->text() != TranslateStrings::cmtr(ipv6map.value("Gateway").toString()) )				  |
      (ui.comboBox_ipv6privacy->currentText() != TranslateStrings::cmtr(ipv6map.value("Privacy").toString())) ) {

    vlist.clear();
    lep.clear();
    slp.clear();
    dict.clear();
    vlist << "IPv6.Configuration";
    dict.insert("Method", sl_ipv6_method.at(ui.comboBox_ipv6method->currentIndex()) );
    dict.insert("PrefixLength", QVariant::fromValue(static_cast<quint8>(ui.spinBox_ipv6prefixlength->value())) );
    dict.insert("Privacy", sl_ipv6_privacy.at(ui.comboBox_ipv6privacy->currentIndex()) );

    lep << ui.lineEdit_ipv6address <<  ui.lineEdit_ipv6gateway;
    slp << "Address" << "Gateway";
    for (int i = 0; i < lep.count(); ++i) {
      s = lep.at(i)->text();
      s = s.simplified(); // really should not be needed with the validator
      if (s.isEmpty() ) s.clear();
      dict.insert(slp.at(i), s);
    } // for

    vlist << QVariant::fromValue(QDBusVariant(dict) );
    shared::processReply(iface_serv->callWithArgumentList(QDBus::AutoDetect, "SetProperty", vlist) );
  } // if ipv6 changed

  // proxy
  // Only update if an entry has changed.
  if ((ui.comboBox_proxymethod->currentText() != TranslateStrings::cmtr(proxmap.value("Method").toString()) )	|
      (ui.lineEdit_proxyservers->text() != proxmap.value("Servers").toStringList().join("\n") )								|
      (ui.lineEdit_proxyexcludes->text() != proxmap.value("Excludes").toStringList().join("\n") )							|
      (ui.lineEdit_proxyurl->text() != proxmap.value("URL").toString()) )																			{

    vlist.clear();
    lep.clear();
    slp.clear();
    dict.clear();
    vlist << "Proxy.Configuration";
    dict.insert("Method", sl_proxy_method.at(ui.comboBox_proxymethod->currentIndex()) );

    lep << ui.lineEdit_proxyurl << ui.lineEdit_proxyservers << ui.lineEdit_proxyexcludes;
    slp << "URL" << "Servers" << "Excludes";
    for (int i = 0; i < lep.count(); ++i) {
      s = lep.at(i)->text();
      s = s.simplified();
      // URL is a single string
      if ( i == 0 ) {
        if (s.isEmpty() ) s.clear();
        dict.insert(slp.at(i), s);
      } // if
      // remanider are an array of strings
      else {
        if (s.isEmpty() ) sl.clear();
        else sl = s.split(' ');
        dict.insert(slp.at(i), sl);
      } //else
    } // for

    vlist << QVariant::fromValue(QDBusVariant(dict) );
    qDebug() << dict;
    shared::processReply(iface_serv->callWithArgumentList(QDBus::AutoDetect, "SetProperty", vlist) );
  } // if proxy changed

  // cleanup
  iface_serv->deleteLater();
  this->accept();
}
void EdrcPlugin::testValidatorTestThree()
{
    // Create validator & test lists
    ConsultResultValidator validator;
    validator.setCrId(1);
    QList<int> selectedIds;
    QList<int> wrongIds;

    // Create criterias using csv {ID;SORT;LABEL;INDENT;WEIGHT}
    QString csv =
            "1;2;++1| GROUP 1;1;2\n"
            "2;3;  ++1| MANDATORY 3.CHILD1;2;2\n"
            "3;4;  ++1| MANDATORY 3.CHILD2;2;2\n"
            "4;5;  ++1| MANDATORY 3.CHILD2;2;2\n"
            "20;6; ;1;8\n"
            "5;7;++1| GROUP 2;1;2\n"
            "6;8;  ++1| MANDATORY 3.CHILD1;2;2\n"
            "21;9; ;1;8\n"
            "7;10;+ - OPTIONAL 1;1;6\n"
            "8;11;+ - OPTIONAL 2;1;6\n"
            "9;12;+ - OPTIONAL 3;1;6\n"
            "10;13; ;1;8\n"
            "11;14;+ - OPTIONAL 1;1;6\n"
            ;
    QList<ConsultResultCriteria> criterias;
    foreach(const QString &line, csv.split("\n", QString::SkipEmptyParts))
        criterias << criteria(line);
    validator.setAvailableCriterias(criterias);


    // Test 1 : missing one mandatory
    selectedIds << 7 << 8 << 9 << 11;
    wrongIds    << 1 << 5;
    testValidator(&validator, selectedIds, wrongIds, "Test3: missing one mandatory 1");
    selectedIds.clear();
    wrongIds.clear();

    // Test 1bis : missing one mandatory
    selectedIds << 2 << 7 << 8 << 9;
    wrongIds    << 1 << 5;
    testValidator(&validator, selectedIds, wrongIds, "Test3: missing one mandatory 2");
    selectedIds.clear();
    wrongIds.clear();

    // Test 1ter : missing one signifiant in the second group
    selectedIds << 1 << 2 << 5;
    wrongIds    << 6;
    testValidator(&validator, selectedIds, wrongIds, "Test3: missing one signifiant in the second group");
    selectedIds.clear();
    wrongIds.clear();

    // Test 2 : missing children
    selectedIds << 1 << 4 << 5;
    wrongIds    << 6;
    testValidator(&validator, selectedIds, wrongIds, "Test3: missing children");
    selectedIds.clear();
    wrongIds.clear();

    // Test 3 : ok
    selectedIds << 1 << 2;
    testValidator(&validator, selectedIds, wrongIds, "Test3: Correct coding 1");
    selectedIds.clear();
    wrongIds.clear();

    // Test 4 : ok
    selectedIds << 1 << 2 << 6 << 5;
    testValidator(&validator, selectedIds, wrongIds, "Test3: Correct coding 2");
    selectedIds.clear();
    wrongIds.clear();

    // Test 5 : ok
    selectedIds << 5 << 6;
    testValidator(&validator, selectedIds, wrongIds, "Test3: Correct coding 3");
    selectedIds.clear();
    wrongIds.clear();
}
Example #27
0
// read zone file, allowing for zones with or without end dates
bool HrZones::read(QFile &file)
{
    defaults_from_user = false;
    scheme.zone_default.clear();
    scheme.zone_default_is_pct.clear();
    scheme.zone_default_name.clear();
    scheme.zone_default_desc.clear();
    scheme.zone_default_trimp.clear();
    scheme.nzones_default = 0;
    ranges.clear();

    // set up possible warning dialog
    warning = QString();
    int warning_lines = 0;
    const int max_warning_lines = 100;

    // macro to append lines to the warning
    #define append_to_warning(s) \
        if (warning_lines < max_warning_lines) \
        warning.append(s);  \
        else if (warning_lines == max_warning_lines) \
        warning.append("...\n"); \
        warning_lines ++;

    // read using text mode takes care of end-lines
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        err = "can't open file";
        return false;
    }
    QTextStream fileStream(&file);

    QRegExp commentrx("\\s*#.*$");
    QRegExp blankrx("^[ \t]*$");
    QRegExp rangerx[] = {
        QRegExp("^\\s*(?:from\\s+)?"                                 // optional "from"
                "((\\d\\d\\d\\d)[-/](\\d{1,2})[-/](\\d{1,2})|BEGIN)" // begin date
                "\\s*([,:]?\\s*(LT)\\s*=\\s*(\\d+))?"                // optional {LT = integer (optional %)}
                "\\s*([,:]?\\s*(RestHr)\\s*=\\s*(\\d+))?"            // optional {RestHr = integer (optional %)}
                "\\s*([,:]?\\s*(MaxHr)\\s*=\\s*(\\d+))?"             // optional {MaxHr = integer (optional %)}
                "\\s*:?\\s*$",                                       // optional :
                Qt::CaseInsensitive),
        QRegExp("^\\s*(?:from\\s+)?"                                 // optional "from"
                "((\\d\\d\\d\\d)[-/](\\d{1,2})[-/](\\d{1,2})|BEGIN)" // begin date
                "\\s+(?:until|to|-)\\s+"                             // until
                "((\\d\\d\\d\\d)[-/](\\d{1,2})[-/](\\d{1,2})|END)?"  // end date
                "\\s*:?,?\\s*((LT)\\s*=\\s*(\\d+))?"                 // optional {LT = integer (optional %)}
                "\\s*:?,?\\s*((RestHr)\\s*=\\s*(\\d+))?"             // optional {RestHr = integer (optional %)}
                "\\s*:?,?\\s*((MaxHr)\\s*=\\s*(\\d+))?"              // optional {MaxHr = integer (optional %)}
                "\\s*:?\\s*$",                                       // optional :
                Qt::CaseInsensitive)
    };
    QRegExp zonerx("^\\s*([^ ,][^,]*),\\s*([^ ,][^,]*),\\s*"
           "(\\d+)\\s*(%?)\\s*(?:,\\s*(\\d+(\\.\\d+)?)\\s*)?$",
           Qt::CaseInsensitive);//
    QRegExp zonedefaultsx("^\\s*(?:zone)?\\s*defaults?\\s*:?\\s*$",
              Qt::CaseInsensitive);

    int lineno = 0;

    // the current range in the file
    // ZoneRange *range = NULL;
    bool in_range = false;
    QDate begin = date_zero, end = date_infinity;
    int lt = 0;
    int restHr = 0;
    int maxHr = 0;
    QList<HrZoneInfo> zoneInfos;

    // true if zone defaults are found in the file (then we need to write them)
    bool zones_are_defaults = false;

    while (! fileStream.atEnd() ) {
        ++lineno;
    QString line = fileStream.readLine();
        int pos = commentrx.indexIn(line, 0);
        if (pos != -1)
            line = line.left(pos);
        if (blankrx.indexIn(line, 0) == 0)
        goto next_line;

    // check for default zone range definition (may be followed by hr zone definitions)
    if (zonedefaultsx.indexIn(line, 0) != -1) {
        zones_are_defaults = true;

        // defaults are allowed only at the beginning of the file
        if (ranges.size()) {
        err = "HR Zone defaults must be specified at head of hr.zones file";
        return false;
        }

        // only one set of defaults is allowed
        if (scheme.nzones_default) {
        err = "Only one set of zone defaults may be specified in hr.zones file";
        return false;
        }

        goto next_line;
    }

    // check for range specification (may be followed by zone definitions)
        for (int r=0; r<2; r++) {
                if (rangerx[r].indexIn(line, 0) != -1) {

                        if (in_range) {

                                // if zones are empty, then generate them
                                HrZoneRange range(begin, end, lt, restHr, maxHr);
                                range.zones = zoneInfos;

                                if (range.zones.empty()) {
                                        if (range.lt > 0) setHrZonesFromLT(range);
                                        else {
                                                err = tr("line %1: read new range without reading "
                                                "any zones for previous one").arg(lineno);
                                                file.close();
                                                return false;
                                        }
                                } else {
                                        qSort(range.zones);
                                }
                                ranges.append(range);
                        }

                        in_range = true;
                        zones_are_defaults = false;
                        zoneInfos.clear();

                        // process the beginning date
                        if (rangerx[r].cap(1) == "BEGIN")
                                begin = date_zero;
                        else {
                                begin = QDate(rangerx[r].cap(2).toInt(),
                                rangerx[r].cap(3).toInt(),
                                rangerx[r].cap(4).toInt());
                        }

                        // process an end date, if any, else it is null
                        if (rangerx[r].cap(5) == "END") end = date_infinity;
                        else if (rangerx[r].cap(6).toInt() || rangerx[r].cap(7).toInt() ||
                                 rangerx[r].cap(8).toInt()) {

                                end = QDate(rangerx[r].cap(6).toInt(),
                                rangerx[r].cap(7).toInt(),
                                rangerx[r].cap(8).toInt());

                        } else {
                                end = QDate();
                        }

                        // set up the range, capturing LT if it's specified
                        // range = new ZoneRange(begin, end);
                        int nLT = (r ? 11 : 7);
                        if (rangerx[r].numCaptures() >= (nLT)) lt = rangerx[r].cap(nLT).toInt();
                        else lt = 0;

                        int nRestHr = (r ? 14 : 10);
                        if (rangerx[r].numCaptures() >= (nRestHr)) restHr = rangerx[r].cap(nRestHr).toInt();
                        else restHr = 0;

                        int nMaxHr = (r ? 17 : 13);
                        if (rangerx[r].numCaptures() >= (nRestHr)) maxHr = rangerx[r].cap(nMaxHr).toInt();
                        else maxHr = 0;

                        // bleck
                        goto next_line;
                }
        }

        // check for zone definition
        if (zonerx.indexIn(line, 0) != -1) {
           if (! (in_range || zones_are_defaults)) {
              err = tr("line %1: read zone without "
                "preceeding date range").arg(lineno);
              file.close();
              return false;
           }

           int lo = zonerx.cap(3).toInt();
           double trimp = zonerx.cap(5).toDouble();

           // allow for zone specified as % of LT
           bool lo_is_pct = false;
           if (zonerx.cap(4) == "%") {
           if (zones_are_defaults) lo_is_pct = true;
           else if (lt > 0) lo = int(lo * lt / 100);
           else {
              err = tr("attempt to set zone based on % of "
                       "LT without setting LT in line number %1.\n").
              arg(lineno);
              file.close();
              return false;
           }
        }

        int hi = -1; // signal an undefined number
        double tr =  zonerx.cap(5).toDouble();

        if (zones_are_defaults) {
           scheme.nzones_default ++;
           scheme.zone_default_is_pct.append(lo_is_pct);
           scheme.zone_default.append(lo);
           scheme.zone_default_name.append(zonerx.cap(1));
           scheme.zone_default_desc.append(zonerx.cap(2));
           scheme.zone_default_trimp.append(trimp);
           defaults_from_user = true;
        }
        else {
           HrZoneInfo zone(zonerx.cap(1), zonerx.cap(2), lo, hi, tr);
           zoneInfos.append(zone);
        }
    }
    next_line: {}
    }

    if (in_range) {
        HrZoneRange range(begin, end, lt, restHr, maxHr);
        range.zones = zoneInfos;
        if (range.zones.empty()) {
            if (range.lt > 0)
            setHrZonesFromLT(range);
        else {
                err = tr("file ended without reading any zones for last range");
                file.close();
                return false;
        }
        }
    else {
        qSort(range.zones);
    }

        ranges.append(range);
    }
    file.close();

    // sort the ranges
    qSort(ranges);

    // set the default zones if not in file
    if (!scheme.nzones_default)  {

        // do we have a zone which is explicitly set?
        for (int i=0; i<ranges.count(); i++) {
                if (ranges[i].hrZonesSetFromLT == false) {
                        // set the defaults using this one!
                        scheme.nzones_default = ranges[i].zones.count();
                        for (int j=0; j<scheme.nzones_default; j++) {
                                scheme.zone_default.append(((double)ranges[i].zones[j].lo / (double)ranges[i].lt) * 100.00);
                                scheme.zone_default_is_pct.append(true);
                                scheme.zone_default_name.append(ranges[i].zones[j].name);
                                scheme.zone_default_desc.append(ranges[i].zones[j].desc);
                                scheme.zone_default_trimp.append(ranges[i].zones[j].trimp);
                        }
                }
        }

        // still not set then reset to defaults as usual
        if (!scheme.nzones_default) initializeZoneParameters();
    }

    // resolve undefined endpoints in ranges and zones
    for (int nr = 0; nr < ranges.size(); nr ++) {
    // clean up gaps or overlaps in zone ranges
    if (ranges[nr].end.isNull())
        ranges[nr].end =
        (nr < ranges.size() - 1) ?
        ranges[nr + 1].begin :
        date_infinity;
    else if ((nr < ranges.size() - 1) &&
         (ranges[nr + 1].begin != ranges[nr].end)) {

        append_to_warning(tr("Setting end date of range %1 "
                 "to start date of range %2.\n").
                  arg(nr + 1).
                  arg(nr + 2)
                  );

        ranges[nr].end = ranges[nr + 1].begin;
    }
    else if ((nr == ranges.size() - 1) &&
         (ranges[nr].end < QDate::currentDate())) {

        append_to_warning(tr("Extending final range %1 to infinite "
                 "to include present date.\n").arg(nr + 1));

        ranges[nr].end = date_infinity;
    }

        if (ranges[nr].lt <= 0) {
            err = tr("LT must be greater than zero in zone "
                     "range %1 of hr.zones").arg(nr + 1);
            return false;
        }

    if (ranges[nr].zones.size()) {
        // check that the first zone starts with zero
        ranges[nr].zones[0].lo = 0;

        // resolve zone end powers
        for (int nz = 0; nz < ranges[nr].zones.size(); nz ++) {
        if (ranges[nr].zones[nz].hi == -1)
            ranges[nr].zones[nz].hi =
            (nz < ranges[nr].zones.size() - 1) ?
            ranges[nr].zones[nz + 1].lo :
            INT_MAX;
        else if ((nz < ranges[nr].zones.size() - 1) &&
             (ranges[nr].zones[nz].hi != ranges[nr].zones[nz + 1].lo)) {
            if (abs(ranges[nr].zones[nz].hi - ranges[nr].zones[nz + 1].lo) > 4) {
            append_to_warning(tr("Range %1: matching top of zone %2 "
                         "(%3) to bottom of zone %4 (%5).\n").
                      arg(nr + 1).
                      arg(ranges[nr].zones[nz].name).
                      arg(ranges[nr].zones[nz].hi).
                      arg(ranges[nr].zones[nz + 1].name).
                      arg(ranges[nr].zones[nz + 1].lo)
                      );
                    }
            ranges[nr].zones[nz].hi = ranges[nr].zones[nz + 1].lo;

        } else if ((nz == ranges[nr].zones.size() - 1) &&
             (ranges[nr].zones[nz].hi < INT_MAX)) {

            append_to_warning(tr("Range %1: setting top of zone %2 from %3 to MAX.\n").
                      arg(nr + 1).
                      arg(ranges[nr].zones[nz].name).
                      arg(ranges[nr].zones[nz].hi)
                      );
            ranges[nr].zones[nz].hi = INT_MAX;
        }
            }
    }
    }

    // mark zones as modified so pages which depend on zones can be updated
    modificationTime = QDateTime::currentDateTime();

    return true;
}
void EdrcPlugin::testValidatorTestOne()
{
    // Create validator & test lists
    ConsultResultValidator validator;
    validator.setCrId(1);
    QList<int> selectedIds;
    QList<int> wrongIds;

    // Create criterias using csv {ID;SORT;LABEL;INDENT;WEIGHT}
    QString csv =
            "0;0;++++ MANDATORY 1;1;1\n"
            "1;1;++++ MANDATORY 2;1;1\n"
            "2;2;++++ MANDATORY 3;1;1\n"
            "3;3;  ++1| MANDATORY 3.CHILD1;2;2\n"
            "4;4;  ++1| MANDATORY 3.CHILD2;2;2\n"
            "5;5;  ++1| MANDATORY 3.CHILD2;2;2\n"
            "6;6; ;1;8\n"
            "7;7;+ - OPTIONAL 1;1;6\n"
            ;
    QList<ConsultResultCriteria> criterias;
    foreach(const QString &line, csv.split("\n", QString::SkipEmptyParts))
        criterias << criteria(line);
    validator.setAvailableCriterias(criterias);


    // Test 1 : missing one mandatory
    selectedIds << 0 << 2 << 3 << 4 << 5;
    wrongIds    << 1;
    testValidator(&validator, selectedIds, wrongIds, "Test1: missing one mandatory 1");
    selectedIds.clear();
    wrongIds.clear();

    // Test 1bis : missing one mandatory
    selectedIds << 0 << 1;
    wrongIds    << 2;
    testValidator(&validator, selectedIds, wrongIds, "Test1: missing one mandatory 2");
    selectedIds.clear();
    wrongIds.clear();

    // Test 1ter : missing one mandatory (child selected but not parent)
    selectedIds << 0 << 1 << 3;
    wrongIds    << 2;
    testValidator(&validator, selectedIds, wrongIds, "Test1: missing one mandatory (child selected but not parent)");
    selectedIds.clear();
    wrongIds.clear();

    // Test 2 : missing children
    selectedIds << 0 << 1 << 2;
    wrongIds    << 3 << 4 << 5;
    testValidator(&validator, selectedIds, wrongIds, "Test1: missing children");
    selectedIds.clear();
    wrongIds.clear();

    // Test 3 : ok
    selectedIds << 0 << 1 << 2 << 3;
    testValidator(&validator, selectedIds, wrongIds, "Test1: Correct coding 1");
    selectedIds.clear();
    wrongIds.clear();

    // Test 4 : ok
    selectedIds << 0 << 1 << 2 << 4;
    testValidator(&validator, selectedIds, wrongIds, "Test1: Correct coding 2");
    selectedIds.clear();
    wrongIds.clear();

    // Test 5 : ok
    selectedIds << 0 << 1 << 2 << 5;
    testValidator(&validator, selectedIds, wrongIds, "Test1: Correct coding 3");
    selectedIds.clear();
    wrongIds.clear();
}
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 );
        }
      }
    }
  }
}
Example #30
0
void
Configuration::readRules(QList<Rule> &rules, int *rules_version_return) {
    // IMPROVE constants.h
    // So wrong by the API specifications, but so right by the end results (no, I don't like doing it this way)
    QSettings s("ProfileMatic", "rules");
    // QSettings s("ajalkane", "ProfileMatic");
    Rule defaultRule = Rule::createDefaultRule();
    int rules_version = s.value("rulesVersion", 0).toInt();
    if (rules_version_return != 0) {
        *rules_version_return = rules_version;
    }
    int size = s.beginReadArray("rules");
    for (int i = 0; i < size; ++i) {
        s.setArrayIndex(i);

        Rule r;
        // r.ruleActive = s.value("ruleActive").toBool();

        _assignRuleId(r, s.value("ruleId"));
        r.setRuleName(s.value("ruleName").toString());
        QList<int> daysList;
        _readIntList(s, "days", "dayId", daysList);
        r.setDays(QSet<int>::fromList(daysList));

        QList<int> locationCells;
        _readIntList(s, "locationCells", "cellId", locationCells);
        r.setLocationCells(QSet<int>::fromList(locationCells));

        QList<QString> wlans;
        _readStringList(s, "wlans", "wlanName", wlans);
        r.setWlan(QSet<QString>::fromList(wlans));

        bool wlanTimeoutOk = false;
        int wlanTimeout = s.value("wlanTimeout").toInt(&wlanTimeoutOk);
        if (wlanTimeoutOk) {
            r.setWlanTimeout(wlanTimeout);
        }

        QString timeStartStr = s.value("timeStart").toString();
        QString timeEndStr = s.value("timeEnd").toString();
        r.setTimeStart(QTime::fromString(timeStartStr));
        r.setTimeEnd(rules_version == 0
                     ? r.getTimeStart().addSecs(60)
                     : QTime::fromString(timeEndStr));
        r.setProfile(s.value("profile").toString());
        r.setRestoreProfile(s.value("restoreProfile", false).toBool());
        bool profileVolumeOk = false;
        int profileVolume = s.value("profileVolume").toInt(&profileVolumeOk);
        if (profileVolumeOk) {
            r.setProfileVolume(profileVolume);
        }

        bool flightModeOk = false;
        int flightMode = s.value("flightMode").toInt(&flightModeOk);
        if (flightModeOk) {
            r.setFlightMode(flightMode);
        }
        r.setRestoreFlightMode(s.value("restoreFlightMode", false).toBool());

        bool powerSavingModeOk = false;
        int powerSavingMode = s.value("powerSavingMode").toInt(&powerSavingModeOk);
        if (powerSavingModeOk) {
            r.setPowerSavingMode(powerSavingMode);
        }
        r.setRestorePowerSavingMode(s.value("restorePowerSavingMode", false).toBool());

        bool blueToothModeOk = false;
        int blueToothMode = s.value("blueToothMode").toInt(&blueToothModeOk);
        if (blueToothModeOk) {
            r.setBlueToothMode(blueToothMode);
        }
        r.setRestoreBlueToothMode(s.value("restoreBlueToothMode", false).toBool());

        bool cellularModeOk = false;
        int cellularMode = s.value("cellularMode").toInt(&cellularModeOk);
        if (cellularModeOk) {
            r.setCellularMode(cellularMode);
        }
        r.setCommandLine(s.value("commandLine").toString());

        QList<PresenceRule *> presenceRules;
        _readPresenceRuleList(s, presenceRules);
        r.setPresenceRules(presenceRules);

        qDeleteAll(presenceRules);
        presenceRules.clear();

        r.setPresenceStatusMessage(s.value("presenceStatusMessage").toString());
        r.setRestorePresence(s.value("restorePresence", r.getRestorePresence()).toBool());
        r.setPresenceChangeType((Rule::PresenceChangeType) s.value("presenceChangeType", (int) Rule::CustomPresenceType).toInt());

        // Make sure default rule is always last, and is created if it does not exist
        if (!r.isDefaultRule()) {
            rules << r;
        } else {
            defaultRule.actionsFrom(r);
        }
        qDebug("Configuration: index %d, ruleId: %s, ruleName: %s", i, qPrintable(r.getRuleId()), qPrintable(r.getRuleName()));
    }
    rules << defaultRule;
    s.endArray();

    // Write rules to finalize conversion
    if (rules_version == 0) {
        qDebug("Writing rules after conversion");
        writeRules(rules);
    }
}