Esempio n. 1
0
    // complementary
    foreach(U2Region complementaryRegion, regionsComplementary){
        translatedSeq.clear();

        U2SequenceImporter importer;
        importer.startSequence(stateInfo, dbiRef, U2ObjectDbi::ROOT_FOLDER, seqObj->getSequenceName()+ " " + resultName + QString(" %1").arg(currentSeq) + " complementary", false);

        QByteArray complementarySeq;
        char* complSeq = NULL;

        int blockCounter = 0;
        qint64 end = complementaryRegion.endPos() - 1  - complementaryRegion.length / 3 * 3;

        for(qint64 i = complementaryRegion.endPos() - 1 ; i > end ;i-=3, blockCounter += 3){
            if( (blockCounter % NUM_DB_READ) == 0 ){
                importer.addBlock(translatedSeq.constData(), translatedSeq.size(), stateInfo);
                complementarySeq.clear();
                seq.clear();
                translatedSeq.clear();
                seq = seqObj->getSequenceData(U2Region(qMax(end + 1, static_cast<qint64>(i - NUM_DB_READ + 1)), qMin(static_cast<qint64>(NUM_DB_READ), i - end)), stateInfo);
                CHECK_OP(stateInfo, );
                complementarySeq.reserve(seq.size());
                complSeq = complementarySeq.data();
                TextUtils::translate(complTT->getOne2OneMapper(), seq, seq.size(), complSeq);
                TextUtils::reverse(complSeq, seq.size());
                blockCounter = 0;

            }
            SAFE_POINT(complSeq != NULL, "complSeq is NULL", );
            translatedSeq.append(aminoTT->translate3to1(complSeq[blockCounter], complSeq[blockCounter + 1], complSeq[blockCounter + 2]));
        }
void DetViewMultiLineRenderer::drawAll(QPainter &p, const QSize &canvasSize, const U2Region &visibleRange) {

    int symbolsPerLine = getSymbolsPerLine(canvasSize.width());
    U2Region oneLineRegion(visibleRange.startPos, symbolsPerLine);
    p.fillRect(QRect(QPoint(0, 0), canvasSize), Qt::white);

    // wide the indent between lines if neccessary
    extraIndent = 0;
    int sequenceLinesCount = visibleRange.length / symbolsPerLine + 1;
    if (ctx->getSequenceLength() == visibleRange.length) {
        int fullContentH = getOneLineHeight() * sequenceLinesCount;
        if (canvasSize.height() > fullContentH && detView->getShift() == 0) {
            extraIndent = (canvasSize.height() - fullContentH) / sequenceLinesCount;
        }
    }

    int indentCounter = 0;
    do {
        // cut the extra space at the end of the sequence
        oneLineRegion.length = qMin(visibleRange.endPos() - oneLineRegion.startPos, oneLineRegion.length);

        singleLinePainter->drawAll(p,
                                   QSize(canvasSize.width(), getOneLineHeight()),
                                   oneLineRegion);

        p.translate(0, getOneLineHeight());
        indentCounter += getOneLineHeight();

        oneLineRegion.startPos += symbolsPerLine;

    } while (oneLineRegion.startPos < visibleRange.endPos());

    // move painter back to [0, 0] position
    p.translate(0, - indentCounter);
}
Esempio n. 3
0
MultipleRangeSelector::MultipleRangeSelector(QWidget* _parent, const QVector<U2Region>& _regions, int _seqLen, bool _isCircular)
:QDialog(_parent)
,seqLen(_seqLen)
,selectedRanges(_regions)
,isCircular(_isCircular)
{

    ui = new Ui_RangeSelectionDialog;
    ui->setupUi(this);
    new HelpButton(this, ui->buttonBox, "17467548");
    ui->buttonBox->button(QDialogButtonBox::Ok)->setText(tr("Go"));
    ui->buttonBox->button(QDialogButtonBox::Cancel)->setText(tr("Cancel"));


    {
        ui->startEdit->setValidator(new QIntValidator(1, seqLen, ui->startEdit));
        ui->endEdit->setValidator(new QIntValidator(1, seqLen, ui->endEdit));

        int w = qMax(((int)log10((double)seqLen))*10, 70);

        ui->startEdit->setMinimumWidth(w);
        ui->endEdit->setMinimumWidth(w);

        if(selectedRanges.isEmpty()){
            ui->startEdit->setText(QString::number(1));
            ui->endEdit->setText(QString::number(seqLen));
        }else{
            U2Region firstRegion = selectedRanges.first();
            ui->startEdit->setText(QString::number(firstRegion.startPos + 1));
            ui->endEdit->setText(QString::number(firstRegion.endPos()));
        }
    }

    {
        QString loc;
        if (selectedRanges.isEmpty()) {
            loc = QString("1..%1").arg(seqLen);
        } else {
            loc = U1AnnotationUtils::buildLocationString(selectedRanges);
        } 
        ui->multipleRegionEdit->setText(loc);
    }
    {
        ui->minButton->setShortcut(QKeySequence(Qt::ALT | Qt::Key_Z));
        ui->maxButton->setShortcut(QKeySequence(Qt::ALT | Qt::Key_X));
        connect(ui->miltipleButton, SIGNAL(toggled(bool)), SLOT(sl_multipleButtonToggled(bool)));

        connect(ui->startEdit, SIGNAL(returnPressed()), SLOT(sl_returnPressed()));
        connect(ui->endEdit, SIGNAL(returnPressed()), SLOT(sl_returnPressed()));
        connect(ui->multipleRegionEdit, SIGNAL(returnPressed()), SLOT(sl_returnPressed()));
        connect(ui->minButton, SIGNAL(clicked()), SLOT(sl_minButton()));
        connect(ui->maxButton, SIGNAL(clicked()), SLOT(sl_maxButton()));

        connect(ui->buttonGroup, SIGNAL(buttonClicked ( QAbstractButton * )), SLOT(sl_buttonClicked(QAbstractButton*)));
        ui->singleButton->toggle();
        sl_buttonClicked(ui->singleButton);
    }
}
void ExtractAnnotatedRegionTask::run() {
    QVector<U2Region> safeLocation = inputAnn->getRegions();
    U2Region::bound(0, inputSeq.length(), safeLocation);
    QList<QByteArray> resParts = U1SequenceUtils::extractRegions(inputSeq.seq, safeLocation, complT, NULL, inputSeq.circular);
    if (aminoT == NULL) { // extension does not work for translated annotations
        if (cfg.extLeft > 0) {
            int annStart = safeLocation.first().startPos;
            int preStart = qMax(0,  annStart - cfg.extLeft);
            int preLen = annStart - preStart;
            QByteArray preSeq = inputSeq.seq.mid(preStart, preLen);
            resParts.prepend(preSeq);

            for (int i = 0; i < safeLocation.size(); ++i) {
                safeLocation[i].startPos -= preLen;
                safeLocation[i].length += preLen;
            }
        }
        if (cfg.extRight) {
            U2Region annRegion = U2Region::containingRegion(safeLocation);
            int annEnd = annRegion.endPos();
            int postEnd = qMin(inputSeq.length(), annEnd + cfg.extRight);
            int postLen = postEnd - annEnd;
            QByteArray postSeq = inputSeq.seq.mid(annEnd, postLen);
            resParts.append(postSeq);

            for (int i = 0; i < safeLocation.size(); ++i) {
                safeLocation[i].length += postLen;
            }
        }
    } else {
        resParts = U1SequenceUtils::translateRegions(resParts, aminoT, inputAnn->isJoin());
    }
    foreach (const QByteArray &seq, resParts) {
        bool onlyOneIteration = false;
        DNASequence s;
        s.info[DNAInfo::ID] = inputSeq.getName();
        if (!cfg.splitJoined || resParts.size() == 1){
            s.seq = resParts.size() == 1 ? resParts.first() : U1SequenceUtils::joinRegions(resParts, cfg.gapLength);
            onlyOneIteration = true;
        }else{
            s.seq = seq;
        }
        s.alphabet = aminoT ? aminoT->getDstAlphabet() : complT ? complT->getDstAlphabet() : inputSeq.alphabet;
        if (aminoT != NULL) {
            s.alphabet = aminoT->getDstAlphabet();
        }else if (complT != NULL) {
            s.alphabet = complT->getDstAlphabet();
        }else {
            s.alphabet = inputSeq.alphabet;
        }
        resultedSeqList.append(s);
        if (onlyOneIteration){
            break;
        }
    }
Esempio n. 5
0
void McaEditorReferenceArea::keyPressEvent(QKeyEvent *event) {
    const int key = event->key();
    bool accepted = false;
    DNASequenceSelection * const selection = ctx->getSequenceSelection();
    U2Region selectedRegion = (NULL != selection && !selection->isEmpty() ? selection->getSelectedRegions().first() : U2Region());

    switch(key) {
    case Qt::Key_Left:
        if (!selectedRegion.isEmpty() && selectedRegion.startPos > 0) {
            selectedRegion.startPos--;
            ctx->getSequenceSelection()->setSelectedRegions(QVector<U2Region>() << selectedRegion);
            ui->getScrollController()->scrollToBase(selectedRegion.startPos, width());
        }
    case Qt::Key_Up:
        accepted = true;
        break;
    case Qt::Key_Right:
        if (!selectedRegion.isEmpty() && selectedRegion.endPos() < ctx->getSequenceLength()) {
            selectedRegion.startPos++;
            ctx->getSequenceSelection()->setSelectedRegions(QVector<U2Region>() << selectedRegion);
            ui->getScrollController()->scrollToBase(selectedRegion.endPos() - 1, width());
        }
    case Qt::Key_Down:
        accepted = true;
        break;
    case Qt::Key_Home:
        ui->getScrollController()->scrollToEnd(ScrollController::Left);
        accepted = true;
        break;
    case Qt::Key_End:
        ui->getScrollController()->scrollToEnd(ScrollController::Right);
        accepted = true;
        break;
    case Qt::Key_PageUp:
        ui->getScrollController()->scrollPage(ScrollController::Left);
        accepted = true;
        break;
    case Qt::Key_PageDown:
        ui->getScrollController()->scrollPage(ScrollController::Right);
        accepted = true;
        break;
    }

    if (accepted) {
        event->accept();
    } else {
        PanView::keyPressEvent(event);
    }
}
bool DetViewMultiLineRenderer::isOnAnnotationLine(const QPoint &p, Annotation *a, int region, const AnnotationSettings *as, const QSize &canvasSize, const U2Region& visibleRange) const {
    qint64 symbolsPerLine = getSymbolsPerLine(canvasSize.width());
    QSize oneLineMinSize(canvasSize.width(), getMinimumHeight());
    U2Region yRange = singleLinePainter->getAnnotationYRange(a, region, as, oneLineMinSize,
                                                            U2Region(visibleRange.startPos, qMin(visibleRange.length, symbolsPerLine)));
    yRange.startPos += (INDENT_BETWEEN_LINES + extraIndent) / 2;
    do {
        if (yRange.contains(p.y())) {
            return true;
        }
        yRange.startPos += getOneLineHeight();
    } while (canvasSize.height() > yRange.endPos());

    return false;
}
CreateRulerDialogController::CreateRulerDialogController(const QSet<QString>& namesToFilter,
                                                         const U2Region& seqRange, int defaultOffset, QWidget* p)
: QDialog(p)
{
    setupUi(this);
    new HelpButton(this, buttonBox, "19766721");
    buttonBox->button(QDialogButtonBox::Ok)->setText(tr("Create"));
    buttonBox->button(QDialogButtonBox::Cancel)->setText(tr("Cancel"));

    setMaximumHeight(layout()->minimumSize().height());

    filter = namesToFilter;

    sampleLabel->setAutoFillBackground(true);

    nameEdit->setText(TextUtils::variate(tr("New ruler"), "_", filter));

    spinBox->setMinimum(INT_MIN + seqRange.length);
    spinBox->setMaximum(INT_MAX);
    spinBox->setValue(seqRange.contains(defaultOffset+1) ? defaultOffset + 1 : spinBox->minimum());

    color = Qt::darkBlue;

    updateColorSample();

    connect(colorButton, SIGNAL(clicked()), SLOT(sl_colorButtonClicked()));
    setWindowIcon(QIcon(":/ugene/images/ugene_16.png"));

}
Esempio n. 8
0
void DeviationGraphAlgorithm::sequenceStrategyWithMemorize(QVector<float>& res, const QByteArray& seq,
    const U2Region& vr, const GSequenceGraphWindowData* d, U2OpStatus &os)
{
    int rsize = d->window / d->step;
    RollingArray<int> raF(rsize);
    RollingArray<int> raS(rsize);
    int endPos = vr.endPos();
    int globalCountF = 0;
    int globalCountS = 0;
    int nextI = 0;
    int firstValue = vr.startPos + d->window - d->step;
    for (int i = vr.startPos; i < endPos; i = nextI)    {
        CHECK_OP(os, );
        nextI = i + d->step;
        QPair<int, int> result = matchOnStep(seq, i, nextI);
        globalCountF += result.first;
        globalCountS += result.second;
        raF.push_back_pop_front(result.first);
        raS.push_back_pop_front(result.second);
        if (i >= firstValue)    {
            int vF = raF.get(0);
            int vS = raS.get(0);
            res.append((globalCountF - globalCountS) / qMax(0.001f, (float)(globalCountF + globalCountS)));
            globalCountF -= vF;
            globalCountS -= vS;
        }
    }
}
bool GTUtilsMSAEditorSequenceArea::isSequenceSelected(HI::GUITestOpStatus &os, const QString &seqName) {
    MSAEditorSequenceArea *msaEditArea = qobject_cast<MSAEditorSequenceArea*>
            (GTWidget::findWidget(os, "msa_editor_sequence_area"));
    CHECK_SET_ERR_RESULT(msaEditArea != NULL, "MsaEditorSequenceArea not found", false);

    QMainWindow* mw = AppContext::getMainWindow()->getQMainWindow();
    MSAEditor* editor = mw->findChild<MSAEditor*>();
    CHECK_SET_ERR_RESULT(editor != NULL, "MsaEditor not found", false);
//Seq names are drawn on widget, so this hack is needed
    U2Region selectedRowsRegion = msaEditArea->getSelectedRows();
    QStringList selectedRowNames;
    for(int x = selectedRowsRegion.startPos; x < selectedRowsRegion.endPos(); x++)
        selectedRowNames.append(editor->getMSAObject()->getRow(x).getName());

    if (selectedRowNames.contains(seqName)) {
        return true;
    }
    return false;
}
Esempio n. 10
0
qint64 RTreeAssemblyAdapter::countReads(const U2Region& r, U2OpStatus& os) {
    if (r == U2_REGION_MAX) {
        return SQLiteReadQuery(QString("SELECT COUNT(*) FROM %1").arg(readsTable), db, os).selectInt64();
    }
    QString qStr = QString("SELECT COUNT(*) FROM %1 AS i WHERE " + RANGE_CONDITION_CHECK).arg(indexTable);
    SQLiteReadQuery q(qStr, db, os);
    q.bindInt64(1, r.endPos());
    q.bindInt64(2, r.startPos);
    return q.selectInt64();
}
Esempio n. 11
0
QString BioStruct3DSubsetEditor::validate() {
    if (regionEdit->isEnabled()) {
        QString regionText = regionEdit->text();
        if (!QRegExp("[0-9]*\\.\\.[0-9]*").exactMatch(regionText)) {
            return QString("invalid region spec %1").arg(regionText);
        }

        BioStruct3DObject *bso = static_cast<BioStruct3DObject*>( objectCombo->itemData(objectCombo->currentIndex()).value<void*>() );
        int chainId = chainCombo->itemData(chainCombo->currentIndex()).value<int>();
        int length = bso->getBioStruct3D().moleculeMap.value(chainId)->residueMap.size();

        U2Region region = getRegion();

        if (region.startPos < 0 || region.startPos >= region.endPos() || region.endPos() > length) {
            return QString("region values out of range %1..%2 (%3..%4)").arg(region.startPos + 1).arg(region.endPos()).arg(1).arg(length);
        }
    }

    return QString("");
}
Esempio n. 12
0
void McaEditorReferenceArea::sl_onSelectionChanged(LRegionsSelection * /*selection*/, const QVector<U2Region> &addedRegions, const QVector<U2Region> &removedRegions) {
    if (addedRegions.size() == 1) {
        const U2Region addedRegion = addedRegions.first();
        qint64 baseToScrollTo = -1;
        if (removedRegions.size() == 1) {
            const U2Region removedRegion = removedRegions.first();
            if (addedRegion.startPos < removedRegion.startPos && addedRegion.endPos() == removedRegion.endPos()) {
                baseToScrollTo = addedRegion.startPos;
            } else if (addedRegion.startPos == removedRegion.startPos && addedRegion.endPos() > removedRegion.endPos()) {
                baseToScrollTo = addedRegion.endPos() - 1;
            } else {
                baseToScrollTo = addedRegion.startPos;
            }
        } else {
            baseToScrollTo = addedRegion.startPos;
        }
        ui->getScrollController()->scrollToBase(static_cast<int>(baseToScrollTo), width());
    }
    emit si_selectionChanged();
}
Esempio n. 13
0
bool DetViewMultiLineRenderer::isOnTranslationsLine(const QPoint &p, const QSize& canvasSize, const U2Region& visibleRange) const {
    qint64 symbolsPerLine = getSymbolsPerLine(canvasSize.width());
    U2Region range(visibleRange.startPos, qMin(symbolsPerLine, visibleRange.length));
    do {
        if (singleLinePainter->isOnTranslationsLine(p, canvasSize, range)) {
            return true;
        }
        range.startPos += symbolsPerLine;
    } while (visibleRange.endPos() > range.endPos());

    return false;
}
Esempio n. 14
0
QString SWMulAlignSubseqPropTag::expandTag(const QVariant & argument) const {
    assert(argument.canConvert<U2Region>());
    U2Region subsequence = argument.value<U2Region>();

    quint64 tagExpansion = 0;
    switch(posType) {
        case START:
            tagExpansion = subsequence.startPos + 1;
            break;
        case END:
            tagExpansion = subsequence.endPos();
            break;
        case LENGTH:
            tagExpansion = subsequence.length;
            break;
        default:
            assert(0);
    }

    return QString::number(tagExpansion);
}
Esempio n. 15
0
WindowStepSelectorWidget::WindowStepSelectorWidget(QWidget* p, const U2Region& winRange, int win, int step) : QWidget(p)
{
    assert(win >= step);

    windowEdit = new QSpinBox(this);
    windowEdit->setRange(winRange.startPos, winRange.endPos());
    windowEdit->setValue(win);
    windowEdit->setAlignment(Qt::AlignRight);
    windowEdit->setObjectName("windowEdit");

    stepsPerWindowEdit = new QSpinBox(this);
    stepsPerWindowEdit->setRange(1, winRange.endPos());
    stepsPerWindowEdit->setValue(win/step);
    stepsPerWindowEdit->setAlignment(Qt::AlignRight);
    stepsPerWindowEdit->setObjectName("stepsPerWindowEdit");

    QFormLayout* l = new QFormLayout(this);
    l->addRow(tr("Window:"), windowEdit);
    l->addRow(tr("Steps per window:"), stepsPerWindowEdit);
    setLayout(l);

}
Esempio n. 16
0
void DetViewMultiLineRenderer::drawSelection(QPainter &p, const QSize &canvasSize, const U2Region &visibleRange) {
    int symbolsPerLine = getSymbolsPerLine(canvasSize.width());
    U2Region oneLineRegion(visibleRange.startPos, symbolsPerLine);

    int indentCounter = 0;
    do {
        // cut the extra space at the end of the sequence
        oneLineRegion.length = qMin(visibleRange.endPos() - oneLineRegion.startPos, oneLineRegion.length);

        singleLinePainter->drawSelection(p,
                                   QSize(canvasSize.width(), getOneLineHeight()),
                                   oneLineRegion);

        p.translate(0, getOneLineHeight());
        indentCounter += getOneLineHeight();

        oneLineRegion.startPos += symbolsPerLine;

    } while (oneLineRegion.startPos < visibleRange.endPos());

    // move painter back to [0, 0] position
    p.translate(0, - indentCounter);
}
Esempio n. 17
0
QByteArray SQLiteSequenceDbi::getSequenceData(const U2DataId& sequenceId, const U2Region& region, U2OpStatus& os) {
    try {
        QByteArray res;
        if (0 == region.length) {
            return res;
        } else if (U2_REGION_MAX != region) {
            res.reserve(region.length);
        }
        // Get all chunks that intersect the region
        SQLiteReadQuery q("SELECT sstart, send, data FROM SequenceData WHERE sequence = ?1 "
            "AND  (send >= ?2 AND sstart < ?3) ORDER BY sstart", db, os);

        q.bindDataId(1, sequenceId);
        q.bindInt64(2, region.startPos);
        q.bindInt64(3, region.endPos());
        qint64 pos = region.startPos;
        qint64 regionLengthToRead = region.length;
        while (q.step()) {
            qint64 sstart = q.getInt64(0);
            qint64 send = q.getInt64(1);
            qint64 length = send - sstart;
            QByteArray data = q.getBlob(2);

            int copyStart = pos - sstart;
            int copyLength = static_cast<int>(qMin(regionLengthToRead, length - copyStart));
            res.append(data.constData() + copyStart, copyLength);
            pos += copyLength;
            regionLengthToRead -= copyLength;

            SAFE_POINT_EXT(regionLengthToRead >= 0,
                os.setError("An error occurred during reading sequence data from dbi."),
                QByteArray());
        }
        return res;
    } catch (const std::bad_alloc &) {
#ifdef UGENE_X86
        os.setError("UGENE ran out of memory during the sequence processing. "
            "The 32-bit UGENE version has a restriction on its memory consumption. Try using the 64-bit version instead.");
#else
        os.setError("Out of memory during the sequence processing.");
#endif
        return QByteArray();
    } catch (...) {
        os.setError("Internal error occurred during the sequence processing.");
        coreLog.error("An exception was thrown during reading sequence data from dbi.");
        return QByteArray();
    }
}
void ExtractAssemblyRegionDialog::sl_regionChanged(const U2Region& newRegion) {
    QString filePath = saveController->getSaveFileName();
    QFileInfo fi(filePath);
    U2Region prevRegion = settings->regionToExtract;
    prevRegion.startPos += 1;
    prevRegion.length -= 1;
    QString stringToReplace = QString::number(prevRegion.startPos) + "_" + QString::number(prevRegion.endPos());
    if (fi.baseName().contains(stringToReplace)) {
        QString baseName = fi.baseName();
        QString newLocation = QString::number(newRegion.startPos + 1) + "_" + QString::number(newRegion.endPos());
        baseName.replace(stringToReplace, newLocation);
        
        filePath = fi.dir().path() + "/" + baseName + "." + fi.completeSuffix();
        saveController->setPath(filePath);
    }
    settings->regionToExtract = newRegion;
}
Esempio n. 19
0
bool SequenceAreaRenderer::drawContent(QPainter &painter, const U2Region &region, const QList<int> &seqIdx, int xStart, int yStart)  const {
    CHECK(!region.isEmpty(), false);
    CHECK(!seqIdx.isEmpty(), false);

    MsaHighlightingScheme* highlightingScheme = seqAreaWgt->getCurrentHighlightingScheme();
    MaEditor* editor = seqAreaWgt->getEditor();

    painter.setPen(Qt::black);
    painter.setFont(editor->getFont());

    MultipleAlignmentObject* maObj = editor->getMaObject();
    SAFE_POINT(maObj != NULL, tr("Alignment object is NULL"), false);
    const MultipleAlignment ma = maObj->getMultipleAlignment();

    //Use dots to draw regions, which are similar to reference sequence
    highlightingScheme->setUseDots(seqAreaWgt->getUseDotsCheckedState());

    int rowHeight = 0;
    foreach (const int rowIndex, seqIdx) {
        rowHeight = drawRow(painter, ma, rowIndex, region, xStart, yStart);
        yStart += ui->getRowHeightController()->getRowHeight(rowIndex);
    }
Esempio n. 20
0
qint64 RTreeAssemblyAdapter::getMaxPackedRow(const U2Region& r, U2OpStatus& os) {
    SQLiteReadQuery q(QString("SELECT MAX(prow1) FROM %1 AS i WHERE (" + RANGE_CONDITION_CHECK + ")").arg(indexTable), db, os);
    q.bindInt64(1, r.endPos());
    q.bindInt64(2, r.startPos);
    return q.selectInt64();
}
Esempio n. 21
0
void BioStruct3DSubsetEditor::setRegion(const U2Region &region) {
    QString text = QString("%1..%2").arg(region.startPos + 1).arg(region.endPos());
    regionEdit->setText(text);
}
void ReadCSVAsAnnotationsTask::run() {
    GUrl url(file);
    IOAdapterId ioId = IOAdapterUtils::url2io(url);
    IOAdapterFactory* iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(ioId);
    QScopedPointer<IOAdapter> io(iof->createIOAdapter());

    if (!io->open(url, IOAdapterMode_Read)) {
        setError(L10N::errorOpeningFileRead(url));
        return;
    }

    QByteArray block(BUFF_SIZE, '\0');
    int blockLen = 0;
    QString text;
    while ((blockLen = io->readBlock(block.data(), BUFF_SIZE)) > 0) {
        int sizeBefore = text.length();
        QString line = QString::fromLocal8Bit(block.data(), blockLen);
        text.append(line);
        if (text.length() != sizeBefore + line.length()) {
            setError(L10N::errorReadingFile(url));
        }
        stateInfo.progress = io->getProgress();
    }
    int maxColumns = 0;
    QList<QStringList> parsedLines = parseLinesIntoTokens(text, config, maxColumns, stateInfo);

    foreach (const QStringList &lineTokens, parsedLines) {
        SharedAnnotationData a(new AnnotationData);
        bool ok = true;
        QString error;
        int startPos = -1;
        int startPosOffset = 0;
        int len = -1;
        int endPos = -1;
        QString groupName;

        for (int column = 0; column < lineTokens.size() && ok; column++) {
            if (column >= config.columns.size()) {
                break;
            }
            const ColumnConfig& columnConf = config.columns.at(column);
            const QString& token = lineTokens.at(column);
            switch(columnConf.role) {
                case ColumnRole_Qualifier:
                    assert(!columnConf.qualifierName.isEmpty());
                    a->qualifiers.append(U2Qualifier(columnConf.qualifierName, token));
                    break;
                case ColumnRole_Name:
                    a->name = token.isEmpty() ? config.defaultAnnotationName : token;
                    ok = Annotation::isValidAnnotationName(a->name);
                    if (!ok) {
                        error = tr("Invalid annotation name: '%1'").arg(a->name);
                    }
                    break;
                case ColumnRole_StartPos:
                    assert(startPos == -1);
                    startPos = token.toInt(&ok) - 1;
                    startPosOffset = columnConf.startPositionOffset;
                    if (!ok) {
                        error = tr("Start offset is not numeric: '%1'").arg(token);
                    }
                    break;
                case ColumnRole_EndPos:
                    assert(endPos == -1);
                    endPos = token.toInt(&ok) + (columnConf.endPositionIsInclusive ? 1 : 0) - 1;
                    if (!ok) {
                        error = tr("End offset is not numeric: '%1'").arg(token);
                    }
                    break;
                case ColumnRole_Length:
                    assert(len == -1);
                    len = token.toInt(&ok);
                    if (!ok) {
                        error = tr("Length is not numeric: '%1'").arg(token);
                    }
                    break;
                case ColumnRole_ComplMark:
                    a->location->strand = (columnConf.complementMark.isEmpty() || token == columnConf.complementMark)
                        ? U2Strand::Complementary : U2Strand::Direct;
                    break;
                case ColumnRole_Group:
                    groupName = token;
                    break;
                default:
                    assert(columnConf.role == ColumnRole_Ignore);
            }
        }

        //add annotation
        if (ok) {
            //set up default name
            if (a->name.isEmpty()) {
                a->name = config.defaultAnnotationName;
            }
            //set up location
            U2Region location;
            if (startPos != -1) {
                location.startPos = startPos + startPosOffset;
                if (endPos != -1) {
                    location.length = endPos - startPos;
                } else {
                    location.length = len;
                }
            } else {
                location.length = len;
                location.startPos = endPos - len;
            }
            if (location.length < 0) {
                location.startPos = location.startPos + location.length;
                location.length = - location.length;
            }
            if (location.startPos < 0 || location.startPos > location.endPos()) {
                algoLog.details(tr("Invalid location: start: %1  len: %2, in line :%3, ignoring")
                    .arg(QString::number(location.startPos)).arg(QString::number(location.length)).arg(lineTokens.join(config.splitToken)));
            } else {
                a->location->regions.append(location);
                result[groupName] << a;
            }
        } else {
            //TODO: make configurable to allow stop parsing on any error!
            algoLog.details(tr("Can't parse line: '%1', error = %2, ignoring").arg(lineTokens.join(config.splitToken)).arg(error));
        }
    }
Esempio n. 23
0
float DetViewMultiLineRenderer::posToXCoordF(qint64 p, const QSize &canvasSize, const U2Region &visibleRange) const {
    CHECK(visibleRange.contains(p), -1);

    qint64 symbolsPerLine = getSymbolsPerLine(canvasSize.width());
    return commonMetrics.charWidth * (p % symbolsPerLine);
}