Example #1
0
void TextLineSegment::layout()
      {
      if (autoplace())
            setUserOff(QPointF());

      TextLineBaseSegment::layout();
      if (parent()) {
            if (textLine()->placeBelow()) {
                  qreal sh = staff() ? staff()->height() : 0.0;
                  rypos() = sh + score()->styleP(StyleIdx::textLinePosBelow) * mag();
                  }
            else
                  rypos() = score()->styleP(StyleIdx::textLinePosAbove) * mag();
            if (autoplace()) {
                  qreal minDistance = spatium() * .7;
                  Shape s1 = shape().translated(pos());
                  if (textLine()->placeAbove()) {
                        qreal d  = system()->topDistance(staffIdx(), s1);
                        if (d > -minDistance)
                              rUserYoffset() = -d - minDistance;
                        }
                  else {
                        qreal d  = system()->bottomDistance(staffIdx(), s1);
                        if (d > -minDistance)
                              rUserYoffset() = d + minDistance;
                        }
                  }
            else
                  adjustReadPos();
            }
      }
Example #2
0
void TextLineSegment::setSelected(bool f)
      {
      Element::setSelected(f);
      if (_text) {
            if (subtype() == SEGMENT_SINGLE || subtype() == SEGMENT_BEGIN) {
                  if (textLine()->beginText())
                        _text->setSelected(f);
                  }
            else if (textLine()->continueText())
                  _text->setSelected(f);
            }
      }
Interpreter::Interpreter(ConsoleWidget *console, VideoWidget *video, MonParameterDB *data, const QString &initScript) :
    m_mutexProg(QMutex::Recursive)
{
    m_initScript = initScript;
    m_initScript.remove(QRegExp("^\\s+"));  // remove initial whitespace
    m_console = console;
    m_video = video;
    m_pixymonParameters = data;
    m_pc = 0;
    m_programming = false;
    m_localProgramRunning = false;
    m_waiting = false;
    m_fastPoll = true;
    m_notified = false;
    m_running = -1; // set to bogus value to force update
    m_chirp = NULL;

    m_renderer = new Renderer(m_video, this);

    connect(m_console, SIGNAL(textLine(QString)), this, SLOT(command(QString)));
    connect(m_console, SIGNAL(controlKey(Qt::Key)), this, SLOT(controlKey(Qt::Key)));
    connect(this, SIGNAL(textOut(QString, QColor)), m_console, SLOT(print(QString, QColor)));
    connect(this, SIGNAL(error(QString)), m_console, SLOT(error(QString)));
    connect(this, SIGNAL(enableConsole(bool)), m_console, SLOT(acceptInput(bool)));
    connect(this, SIGNAL(prompt(QString)), m_console, SLOT(prompt(QString)));
    connect(this, SIGNAL(consoleCommand(QString)), m_console, SLOT(command(QString)));
    connect(this, SIGNAL(videoInput(VideoWidget::InputMode)), m_video, SLOT(acceptInput(VideoWidget::InputMode)));
    connect(m_video, SIGNAL(selection(int,int,int,int)), this, SLOT(handleSelection(int,int,int,int)));

    prompt();

    m_run = true;
}
Example #4
0
Interpreter::Interpreter(ConsoleWidget *console, VideoWidget *video) : m_mutexProg(QMutex::Recursive)
{
    m_console = console;
    m_video = video;
    m_pc = 0;
    m_programming = false;
    m_localProgramRunning = false;
    m_rcount = 0;
    m_waiting = false;
    m_fastPoll = true;
    m_notified = false;
    m_pendingCommand = NONE;
    m_running = -1; // set to bogus value to force update
    m_chirp = NULL;

    m_renderer = new Renderer(m_video);

    connect(m_console, SIGNAL(textLine(QString)), this, SLOT(command(QString)));
    connect(m_console, SIGNAL(controlKey(Qt::Key)), this, SLOT(controlKey(Qt::Key)));
    connect(this, SIGNAL(textOut(QString, QColor)), m_console, SLOT(print(QString, QColor)));
    connect(this, SIGNAL(error(QString)), m_console, SLOT(error(QString)));
    connect(this, SIGNAL(enableConsole(bool)), m_console, SLOT(acceptInput(bool)));
    connect(this, SIGNAL(prompt(QString)), m_console, SLOT(prompt(QString)));
    connect(this, SIGNAL(videoInput(VideoWidget::InputMode)), m_video, SLOT(acceptInput(VideoWidget::InputMode)));
    connect(m_video, SIGNAL(selection(int,int,int,int)), this, SLOT(handleSelection(int,int,int,int)));

    m_run = true;
    start();
}
Example #5
0
QVariant TextLineSegment::propertyDefault(P_ID id) const
      {
      switch (id) {
            case P_ID::PLACEMENT:
                  return textLine()->propertyDefault(id);
            default:
                  return TextLineBaseSegment::propertyDefault(id);
            }
      }
Example #6
0
bool TextLineSegment::setProperty(P_ID id, const QVariant& v)
      {
      switch (id) {
            case P_ID::PLACEMENT:
                  return textLine()->setProperty(id, v);
            default:
                  return TextLineBaseSegment::setProperty(id, v);
            }
      }
Example #7
0
void KEdit::search_slot()
{

    int line, col;

    if(!srchdialog)
        return;

    QString to_find_string = srchdialog->getText();
    getCursorPosition(&line, &col);

    // srchdialog->get_direction() is true if searching backward

    if(last_search != NONE && srchdialog->get_direction())
    {
        col = col - pattern.length() - 1;
    }

again:
    int result = doSearch(to_find_string, srchdialog->case_sensitive(), false, (!srchdialog->get_direction()), line, col);

    if(!result)
    {
        if(!srchdialog->get_direction())
        { // forward search

            int query = KMessageBox::questionYesNo(srchdialog, i18n("End of document reached.\n"
                                                                    "Continue from the beginning?"),
                                                   i18n("Find"), KStdGuiItem::cont(), i18n("Stop"));
            if(query == KMessageBox::Yes)
            {
                line = 0;
                col = 0;
                goto again;
            }
        }
        else
        { // backward search

            int query = KMessageBox::questionYesNo(srchdialog, i18n("Beginning of document reached.\n"
                                                                    "Continue from the end?"),
                                                   i18n("Find"), KStdGuiItem::cont(), i18n("Stop"));
            if(query == KMessageBox::Yes)
            {
                QString string = textLine(numLines() - 1);
                line = numLines() - 1;
                col = string.length();
                last_search = BACKWARD;
                goto again;
            }
        }
    }
    else
    {
        emit CursorPositionChanged();
    }
}
Example #8
0
void TextLineSegment::resetProperty(P_ID id)
      {
      switch (id) {
            case P_ID::PLACEMENT:
                  return textLine()->resetProperty(id);

            default:
                  return TextLineBaseSegment::resetProperty(id);
            }
      }
Example #9
0
PropertyStyle TextLineSegment::propertyStyle(P_ID id) const
      {
      switch (id) {
            case P_ID::PLACEMENT:
                  return textLine()->propertyStyle(id);

            default:
                  return TextLineBaseSegment::propertyStyle(id);
            }
      }
Example #10
0
void ConsoleWidget::keyPressEvent(QKeyEvent *event)
{
    QString line;

    if (!isReadOnly())
    {
        moveCursor(QTextCursor::End);

        if (event->key()==Qt::Key_Return)
        {
            QTextCursor cursor = textCursor();
            line = cursor.block().text();

            line.remove(0, m_prompt.size()); // get rid of prompt (assume it's just the first character)
            // propagate newline before we send text
            QPlainTextEdit::keyPressEvent(event);
            // send text
            emit textLine(line);
            return;

        }
        else if (event->key()==Qt::Key_Up)
        {
            emit controlKey(Qt::Key_Up);
            return;
        }
        else if (event->key()==Qt::Key_Down)
        {
            emit controlKey(Qt::Key_Down);
            return;
        }
        else if (event->key()==Qt::Key_Backspace)
        {
            QTextCursor cursor = textCursor();

            line = cursor.block().text();
            // don't propagate backspace if it means we're going to delete the prompt
            if (line.size()<=m_prompt.size())
                return;
        }
        else if (event->matches(QKeySequence::Copy)) // break key
            emit controlKey(Qt::Key_Escape);
        else
        {
            // make sure when we're typing, there's a prompt
            QTextCursor cursor = textCursor();

            line = cursor.block().text();
            if (line.left(m_prompt.size())!=m_prompt)
                prompt(m_prompt);
        }
    }

    QPlainTextEdit::keyPressEvent(event);
}
Example #11
0
void SvnSyncDialog::UpdateUrl(const wxString& rootDir)
{
    SvnInfo svnInfo;
    m_plugin->DoGetSvnInfoSync(svnInfo, rootDir);

    wxString textLine(_("Root URL:  "));
    if(svnInfo.m_sourceUrl.IsEmpty()) {
        textLine += _("<not applicable>");
    } else {
        textLine += svnInfo.m_sourceUrl;
    }
    m_staticTextSvnInfo->SetLabel(textLine);
}
void ConsoleWidget::command(QString text)
{
    text.remove(QRegExp("^\\s+")); // remove leading whitespace
    if (text=="")
        return;
    handleColor(CW_DEFAULT_COLOR);
    prompt();
    if (!text.endsWith('\n'))
        text = text + '\n';
    insertPlainText(text);

    emit textLine(text);
}
void DigraphMultiLineEdit::keyPressEvent( QKeyEvent* event ) {
    //cout << "txt='" << event->text() << "' asc=" << event->ascii() << "; k=" << event->key() << " count=" << event->count() << endl;
    if( digraphEnabled ) {
        // We consider only printable keys.  Control keys are processed normally.
        // I'm not sure if this test covers all the cases though.
        if( event->count() > 0 ) {
            if( event->key() == Key_Backspace ) {
                int line;
                int col;
                getCursorPosition( &line, &col );
                if( line + col > 0 ) {
                    if( buffer.isNull() ) {
                        QString charToDelete( textLine( line ).mid( col - 1, 1 ) );
                        buffer = charToDelete;
                    }
                    else 
                        buffer = QString::null;
                }
            }
            else {
                if( !buffer.isNull() ) {
                    buffer += event->text();
                    const QString newChar( Util::getDigraph( buffer ) );
                    if( newChar == QString::null )
                        buffer = QString::null;
                    else {
                        QKeyEvent* digraphEvent = new QKeyEvent( QEvent::KeyPress, 0, 0, 0, newChar, event->isAutoRepeat(), 0 );
                        QMultiLineEdit::keyPressEvent( digraphEvent );
                        return;
                    }
                }
            }
        }
    }
    QMultiLineEdit::keyPressEvent( event );
}
Example #14
0
int KateLineLayout::length( ) const
{
  return textLine()->length();
}
Example #15
0
void TextLineSegment::draw(QPainter* painter) const
      {
      TextLine* tl   = textLine();
      qreal _spatium = spatium();

      qreal textlineLineWidth    = tl->lineWidth().val() * _spatium;
      qreal textlineTextDistance = _spatium * .5;

      QPointF pp2(pos2());

      QColor color;
      bool normalColor = false;
      if (selected() && !(score() && score()->printing()))
            color = MScore::selectColor[0];
      else if (!visible())
            color = Qt::gray;
      else {
            color = curColor();
            normalColor = true;
            }

      qreal l = 0.0;
      int sym = subtype() == SEGMENT_MIDDLE ? tl->continueSymbol() : tl->beginSymbol();
      if (_text) {
            SpannerSegmentType st = subtype();
            if (
               ((st == SEGMENT_SINGLE || st == SEGMENT_BEGIN) && (tl->beginTextPlace() == PLACE_LEFT))
               || ((st == SEGMENT_MIDDLE || st == SEGMENT_END) && (tl->continueTextPlace() == PLACE_LEFT))
               ) {
                  QRectF bb(_text->bbox());
                  l = _text->pos().x() + bb.width() + textlineTextDistance;
                  }
            painter->translate(_text->pos());
            painter->setPen(normalColor ? _text->curColor() : color);
            _text->draw(painter);
            painter->translate(-_text->pos());
            }
      else if (sym != -1) {
            const QRectF& bb = symbols[score()->symIdx()][sym].bbox(magS());
            qreal h = bb.height() * .5;
            QPointF o = tl->beginSymbolOffset() * _spatium;
            painter->setPen(color);
            symbols[score()->symIdx()][sym].draw(painter, 1.0, QPointF(o.x(), h + o.y()));
            l = bb.width() + textlineTextDistance;
            }

      QPen pen(normalColor ? tl->lineColor() : color, textlineLineWidth);
      pen.setStyle(tl->lineStyle());
      painter->setPen(pen);

      if (subtype() == SEGMENT_SINGLE || subtype() == SEGMENT_END) {
            if (tl->endSymbol() != -1) {
                  int sym = tl->endSymbol();
                  const QRectF& bb = symbols[score()->symIdx()][sym].bbox(magS());
                  qreal h = bb.height() * .5;
                  QPointF o = tl->endSymbolOffset() * _spatium;
                  pp2.setX(pp2.x() - bb.width() + textlineTextDistance);
                  symbols[score()->symIdx()][sym].draw(painter, 1.0, QPointF(pp2.x() + textlineTextDistance + o.x(), h + o.y()));
                  }
            }

      QPointF pp1(l, 0.0);

      if (tl->beginHook() && tl->beginHookType() == HOOK_45)
            pp1.rx() += fabs(tl->beginHookHeight().val() * _spatium * .4);
      if (tl->endHook() && tl->endHookType() == HOOK_45)
            pp2.rx() -= fabs(tl->endHookHeight().val() * _spatium * .4);

      painter->drawLine(QLineF(pp1.x(), pp1.y(), pp2.x(), pp2.y()));

      if (tl->beginHook()) {
            qreal hh = tl->beginHookHeight().val() * _spatium;
            if (subtype() == SEGMENT_SINGLE || subtype() == SEGMENT_BEGIN) {
                  if (tl->beginHookType() == HOOK_45)
                        painter->drawLine(QLineF(pp1.x(), pp1.y(), pp1.x() - fabs(hh * .4), pp1.y() + hh));
                  else
                        painter->drawLine(QLineF(pp1.x(), pp1.y(), pp1.x(), pp1.y() + hh));
                  }
            }
      if (tl->endHook()) {
            qreal hh = tl->endHookHeight().val() * _spatium;
            if (subtype() == SEGMENT_SINGLE || subtype() == SEGMENT_END) {
                  if (tl->endHookType() == HOOK_45)
                        painter->drawLine(QLineF(pp2.x(), pp2.y(), pp2.x() + fabs(hh * .4), pp2.y() + hh));
                  else
                        painter->drawLine(QLineF(pp2.x(), pp2.y(), pp2.x(), pp2.y() + hh));
                  }
            }
      }
Example #16
0
bool KateLineLayout::isValid( ) const
{
  return line() != -1 && layout() && textLine();
}
void ConsoleWidget::keyPressEvent(QKeyEvent *event)
{
    QString line;

    if (!isReadOnly())
    {
        m_timer.stop();

        if (event->modifiers()==0 || event->modifiers()==Qt::ShiftModifier || event->matches(QKeySequence::Paste))
            moveCursor(QTextCursor::End);

        QTextCursor cursor = textCursor();

        if (event->key()==Qt::Key_Return)
        {
            line = cursor.block().text();

            line.remove(0, m_prompt.size()); // get rid of prompt
            line.remove(QRegExp("^\\s+")); //remove leading whitespace
            line.remove(QRegExp("\\s+$")); //remove trailing whitespace
            // propagate newline before we send text
            QPlainTextEdit::keyPressEvent(event);
            m_timer.start();
            if (line.size()==0)
                return;
            // add line to history if it's not the same as previous line
            if (m_history.size()==0 || line!=m_history.back())
                m_history << line;
            // remove least recent line if we're up against the max history parameter
            if (m_history.size()==CW_MAXHIST+1)
                m_history.removeFirst();
            m_histIndex = -1;
            // send text
            emit textLine(line);
            return;

        }
        else if (event->key()==Qt::Key_Up)
        {
            emit controlKey(Qt::Key_Up);
            handleHistory(false);
            return;
        }
        else if (event->key()==Qt::Key_Down)
        {
            emit controlKey(Qt::Key_Down);
            handleHistory(true);
            return;
        }
        else if (event->key()==Qt::Key_Backspace)
        {
            line = cursor.block().text();
            // don't propagate backspace if it means we're going to delete the prompt
            if (line.size()<=m_prompt.size())
                return;
        }
        else if (event->matches(QKeySequence::Copy)) // break key
            emit controlKey(Qt::Key_Escape);
    }

    QPlainTextEdit::keyPressEvent(event);
}
Example #18
0
void TextLineSegment::spatiumChanged(qreal ov, qreal nv)
      {
      textLine()->spatiumChanged(ov, nv);
      if (_text)
            _text->spatiumChanged(ov, nv);
      }
Example #19
0
void TextLineSegment::styleChanged()
      {
      textLine()->styleChanged();
      }
Example #20
0
void TextLineSegment::layout1()
      {
      TextLine* tl = textLine();
      if (!tl->diagonal())
            _userOff2.setY(0);
      switch (subtype()) {
            case SEGMENT_SINGLE:
            case SEGMENT_BEGIN:
                  if (tl->beginText()) {
                        if (_text == 0) {
                              _text = new Text(*tl->beginText());
                              _text->setFlag(ELEMENT_MOVABLE, false);
                              _text->setParent(this);
                              }
                        }
                  else {
                        delete _text;
                        _text = 0;
                        }
                  break;
            case SEGMENT_MIDDLE:
            case SEGMENT_END:
                  if (tl->continueText()) {
                        if (_text == 0) {
                              _text = new Text(*tl->continueText());
                              _text->setFlag(ELEMENT_MOVABLE, false);
                              _text->setParent(this);
                              }
                        }
                  else {
                        delete _text;
                        _text = 0;
                        }
                  break;
            }
      if (_text)
            _text->layout();

      QPointF pp1;
      QPointF pp2(pos2());

      if (!_text && pp2.y() != 0) {
            setbbox(QRectF(pp1, pp2).normalized());
            return;
            }
      qreal y1 = point(-textLine()->lineWidth());
      qreal y2 = -y1;

      int sym = textLine()->beginSymbol();
      if (_text) {
            qreal h = _text->height();
            if (textLine()->beginTextPlace() == PLACE_ABOVE)
                  y1 = -h;
            else if (textLine()->beginTextPlace() == PLACE_BELOW)
                  y2 = h;
            else {
                  y1 = -h * .5;
                  y2 = h * .5;
                  }
            }
      else if (sym != -1) {
            qreal hh = symbols[score()->symIdx()][sym].height(magS()) * .5;
            y1 = -hh;
            y2 = hh;
            }
      if (textLine()->endHook()) {
            qreal h = point(textLine()->endHookHeight());
            if (h > y2)
                  y2 = h;
            else if (h < y1)
                  y1 = h;
            }
      if (textLine()->beginHook()) {
            qreal h = point(textLine()->beginHookHeight());
            if (h > y2)
                  y2 = h;
            else if (h < y1)
                  y1 = h;
            }
      bbox().setRect(.0, y1, pp2.x(), y2 - y1);
      }
Example #21
0
void Application::DrawText( const Reader& reader, Book& book )
{
	sf::Shape bg;
	bg = sf::Shape::Rectangle( 5, 5, m_textOutputWidth, m_screenHeight-5, sf::Color( 182, 220, 255 ) );
	m_app.Draw( bg );

	int yPos = 0;
	int xPos = 10;

	vector<string> lstLines = book.GetReadLines();

	for ( int i = 0; i < lstLines.size(); i++ )
	{
		yPos += m_fontSize;
		cout << i << ", " << lstLines[i] << endl;
		string currentLine = lstLines[i];
		int beginIndex = 0;
		int endIndex = 0;
		int pulledLines = 1;

		if ( i == reader.GetCurrentLine() )
		{
			cout << endl << endl;
			cout << "-------------------------------------------" << endl;
			cout << endl << "WRITE LINE" << endl << currentLine << endl;
			cout << endl << "SPLIT UP" << endl;
		}

		// Account for word-wrapping
		while ( currentLine.length() * (m_fontSize/2) > m_textOutputWidth )
		{
			endIndex = ( 2 * m_textOutputWidth / m_fontSize ) - 10;
			// Adjust endIndex to be where a ' ' is.
			while ( currentLine[ endIndex ] != ' ' )
			{
				endIndex++;
			}

			sf::String textLine( currentLine.substr( beginIndex, endIndex ),
								m_font, m_fontSize );
			textLine.SetPosition( xPos, yPos );
			textLine.SetColor( sf::Color( 0, 0, 0 ) );

			if ( i == reader.GetCurrentLine() )
			{
				cout << pulledLines << ": " << currentLine.substr( beginIndex, endIndex ) << endl;
			}

			m_app.Draw( textLine );
			yPos += m_fontSize;
			currentLine.erase( beginIndex, endIndex );
			pulledLines++;
		}

		// Output remaining line
		sf::String textLine( currentLine, m_font, m_fontSize );
		textLine.SetPosition( xPos, yPos );
		textLine.SetColor( sf::Color( 0, 0, 0 ) );

		if ( i == reader.GetCurrentLine() )
		{
			cout << pulledLines << ": " << currentLine << endl;
		}

		m_app.Draw( textLine );
		yPos += m_fontSize;
	}

	sf::Sprite character;
	character.SetImage( m_talker );
	character.SetSubRect( sf::IntRect( m_characterFrame * 112, 0, m_characterFrame * 112 + 112, 192 ) );
	character.SetPosition( 600, m_screenHeight - (m_talker.GetHeight()*2) );
	character.SetScale( 2, 2 );
	m_app.Draw( character );

	if ( ++m_characterFrame > 2 )
	{
		m_characterFrame = 0;
	}
}
Example #22
0
  void CharacterAnalysis::analyze()
  {
    timespec startTime;
    getTimeMonotonic(&startTime);

    pipeline_data->clearThresholds();
    pipeline_data->thresholds = produceThresholds(pipeline_data->crop_gray, config);

    timespec contoursStartTime;
    getTimeMonotonic(&contoursStartTime);

    pipeline_data->textLines.clear();

    for (unsigned int i = 0; i < pipeline_data->thresholds.size(); i++)
    {
      TextContours tc(pipeline_data->thresholds[i]);

      allTextContours.push_back(tc);
    }

    if (config->debugTiming)
    {
      timespec contoursEndTime;
      getTimeMonotonic(&contoursEndTime);
      cout << "  -- Character Analysis Find Contours Time: " << diffclock(contoursStartTime, contoursEndTime) << "ms." << endl;
    }
    //Mat img_equalized = equalizeBrightness(img_gray);

    timespec filterStartTime;
    getTimeMonotonic(&filterStartTime);

    for (unsigned int i = 0; i < pipeline_data->thresholds.size(); i++)
    {
      this->filter(pipeline_data->thresholds[i], allTextContours[i]);

      if (config->debugCharAnalysis)
        cout << "Threshold " << i << " had " << allTextContours[i].getGoodIndicesCount() << " good indices." << endl;
    }

    if (config->debugTiming)
    {
      timespec filterEndTime;
      getTimeMonotonic(&filterEndTime);
      cout << "  -- Character Analysis Filter Time: " << diffclock(filterStartTime, filterEndTime) << "ms." << endl;
    }

    PlateMask plateMask(pipeline_data);
    plateMask.findOuterBoxMask(allTextContours);

    pipeline_data->hasPlateBorder = plateMask.hasPlateMask;
    pipeline_data->plateBorderMask = plateMask.getMask();

    if (plateMask.hasPlateMask)
    {
      // Filter out bad contours now that we have an outer box mask...
      for (unsigned int i = 0; i < pipeline_data->thresholds.size(); i++)
      {
        filterByOuterMask(allTextContours[i]);
      }
    }

    int bestFitScore = -1;
    int bestFitIndex = -1;
    for (unsigned int i = 0; i < pipeline_data->thresholds.size(); i++)
    {

      int segmentCount = allTextContours[i].getGoodIndicesCount();

      if (segmentCount > bestFitScore)
      {
        bestFitScore = segmentCount;
        bestFitIndex = i;
        bestThreshold = pipeline_data->thresholds[i];
        bestContours = allTextContours[i];
      }
    }

    if (this->config->debugCharAnalysis)
      cout << "Best fit score: " << bestFitScore << " Index: " << bestFitIndex << endl;

    if (bestFitScore <= 1)
    {
      pipeline_data->disqualified = true;
      pipeline_data->disqualify_reason = "Low best fit score in characteranalysis";
      return;
    }

    //getColorMask(img, allContours, allHierarchy, charSegments);

    if (this->config->debugCharAnalysis)
    {
      Mat img_contours = bestContours.drawDebugImage(bestThreshold);

      displayImage(config, "Matching Contours", img_contours);
    }

    LineFinder lf(pipeline_data);
    vector<vector<Point> > linePolygons = lf.findLines(pipeline_data->crop_gray, bestContours);

    vector<TextLine> tempTextLines;
    for (unsigned int i = 0; i < linePolygons.size(); i++)
    {
      vector<Point> linePolygon = linePolygons[i];

      LineSegment topLine = LineSegment(linePolygon[0].x, linePolygon[0].y, linePolygon[1].x, linePolygon[1].y);
      LineSegment bottomLine = LineSegment(linePolygon[3].x, linePolygon[3].y, linePolygon[2].x, linePolygon[2].y);

      vector<Point> textArea = getCharArea(topLine, bottomLine);

      TextLine textLine(textArea, linePolygon, pipeline_data->crop_gray.size());

      tempTextLines.push_back(textLine);
    }

    filterBetweenLines(bestThreshold, bestContours, tempTextLines);

    // Sort the lines from top to bottom.
    std::sort(tempTextLines.begin(), tempTextLines.end(), sort_text_line);

    // Now that we've filtered a few more contours, re-do the text area.
    for (unsigned int i = 0; i < tempTextLines.size(); i++)
    {
      vector<Point> updatedTextArea = getCharArea(tempTextLines[i].topLine, tempTextLines[i].bottomLine);
      vector<Point> linePolygon = tempTextLines[i].linePolygon;
      if (updatedTextArea.size() > 0 && linePolygon.size() > 0)
      {
        pipeline_data->textLines.push_back(TextLine(updatedTextArea, linePolygon, pipeline_data->crop_gray.size()));
      }

    }

    pipeline_data->plate_inverted = isPlateInverted();


    if (pipeline_data->textLines.size() > 0)
    {
      int confidenceDrainers = 0;
      int charSegmentCount = this->bestContours.getGoodIndicesCount();
      if (charSegmentCount == 1)
        confidenceDrainers += 91;
      else if (charSegmentCount < 5)
        confidenceDrainers += (5 - charSegmentCount) * 10;

      // Use the angle for the first line -- assume they'll always be parallel for multi-line plates
      int absangle = abs(pipeline_data->textLines[0].topLine.angle);
      if (absangle > config->maxPlateAngleDegrees)
        confidenceDrainers += 91;
      else if (absangle > 1)
        confidenceDrainers += (config->maxPlateAngleDegrees - absangle) ;

      // If a multiline plate has only one line, disqualify
      if (pipeline_data->isMultiline && pipeline_data->textLines.size() < 2)
      {
        if (config->debugCharAnalysis)
          std::cout << "Did not detect multiple lines on multi-line plate" << std::endl;
        confidenceDrainers += 95;
      }

      if (confidenceDrainers >= 90)
      {
        pipeline_data->disqualified = true;
        pipeline_data->disqualify_reason = "Low confidence in characteranalysis";
      }
      else
      {
        float confidence = 100 - confidenceDrainers;
        pipeline_data->confidence_weights.setScore("CHARACTER_ANALYSIS_SCORE", confidence, 1.0);
      }
    }
    else
    {
        pipeline_data->disqualified = true;
        pipeline_data->disqualify_reason = "No text lines found in characteranalysis";
    }

    if (config->debugTiming)
    {
      timespec endTime;
      getTimeMonotonic(&endTime);
      cout << "Character Analysis Time: " << diffclock(startTime, endTime) << "ms." << endl;
    }

    // Draw debug dashboard
    if (this->pipeline_data->config->debugCharAnalysis && pipeline_data->textLines.size() > 0)
    {
      vector<Mat> tempDash;
      for (unsigned int z = 0; z < pipeline_data->thresholds.size(); z++)
      {
        Mat tmp(pipeline_data->thresholds[z].size(), pipeline_data->thresholds[z].type());
        pipeline_data->thresholds[z].copyTo(tmp);
        cvtColor(tmp, tmp, CV_GRAY2BGR);

        tempDash.push_back(tmp);
      }

      Mat bestVal(this->bestThreshold.size(), this->bestThreshold.type());
      this->bestThreshold.copyTo(bestVal);
      cvtColor(bestVal, bestVal, CV_GRAY2BGR);

      for (unsigned int z = 0; z < this->bestContours.size(); z++)
      {
        Scalar dcolor(255,0,0);
        if (this->bestContours.goodIndices[z])
          dcolor = Scalar(0,255,0);
        drawContours(bestVal, this->bestContours.contours, z, dcolor, 1);
      }
      tempDash.push_back(bestVal);
      displayImage(config, "Character Region Step 1 Thresholds", drawImageDashboard(tempDash, bestVal.type(), 3));
    }
  }
Example #23
0
/* antlarr: KDE 4: make it const QString & */
int KEdit::doReplace(QString s_pattern, bool case_sensitive,
	   bool wildcard, bool forward, int line, int col, bool replace_all){


  (void) wildcard; // reserved for possible extension to regex

  int line_counter, length;
  int pos = -1;

  QString string;
  QString stringnew;
  QString replacement;

  replacement = replace_dialog->getReplaceText();
  line_counter = line;
  replace_all_col = col;

  if(forward){

    int num_lines = numLines();

    while (line_counter < num_lines){

      string = textLine(line_counter);

      if (replace_all){
	pos = string.find(s_pattern, replace_all_col, case_sensitive);
      }
      else{
	pos = string.find(s_pattern, line_counter == line ? col : 0, case_sensitive);
      }

      if (pos == -1 ){
	line_counter++;
	replace_all_col = 0;
	replace_all_line = line_counter;
      }

      if( pos != -1){

	length = s_pattern.length();

	if(replace_all){ // automatic

          stringnew = string.copy();
          do 
          {  
	    stringnew.replace(pos,length,replacement);

	    replace_all_col = pos + replacement.length();
	    replace_all_line = line_counter;

            pos = stringnew.find(s_pattern, replace_all_col, case_sensitive);
          }
          while( pos != -1); 

	  removeLine(line_counter);
	  insertLine(stringnew,line_counter);

	  setModified(true);
	}
	else{ // interactive

	  setCursorPosition( line_counter , pos, false );

	  for(int l = 0 ; l < length; l++){
	    cursorRight(true);
	  }

	  setCursorPosition( line_counter , pos + length, true );
	  pattern = s_pattern;
	  last_replace = FORWARD;
	  can_replace = true;

	  return 1;

	}

      }
    }
  }
  else{ // searching backwards

    while(line_counter >= 0){

      string = textLine(line_counter);

      int line_length = string.length();

      if( replace_all ){
        if (replace_all_col < 0)
          pos = -1;
        else
          pos = string.findRev(s_pattern, replace_all_col , case_sensitive);
      }
      else{
        if ((line == line_counter) && (col < 0))
          pos = -1;
        else
          pos = string.findRev(s_pattern,
			   line == line_counter ? col : line_length , case_sensitive);
      }

      if (pos == -1 ){
	line_counter--;

        replace_all_col = 0;
	if(line_counter >= 0){
	  string = textLine(line_counter);
	  replace_all_col = string.length();

	}
	replace_all_line = line_counter;
      }


      if (pos != -1){
	length = s_pattern.length();

	if(replace_all){ // automatic

	  stringnew = string.copy();
	  stringnew.replace(pos,length,replacement);

	  removeLine(line_counter);
	  insertLine(stringnew,line_counter);

	  replace_all_col = pos-length;
	  replace_all_line = line_counter;
	  if (replace_all_col < 0)
	  {
             line_counter--;

             if(line_counter >= 0){
                string = textLine(line_counter);
                replace_all_col = string.length();
             }
             replace_all_line = line_counter;
	  }

	  setModified(true);
	}
	else{ // interactive

	  //	  printf("line_counter %d pos %d col %d\n",line_counter, pos,col);
	  if( ! (line == line_counter && pos > col ) ){

	    setCursorPosition(line_counter, pos + length ,false );

	    for(int l = 0 ; l < length; l++){
	      cursorLeft(true);
	    }

	    setCursorPosition(line_counter, pos ,true );
	    pattern = s_pattern;

	    last_replace = BACKWARD;
	    can_replace = true;

	    return 1;
	  }
	}
      }
    }
  }

  return 0;

}
Example #24
0
void KEdit::replace_search_slot(){

  int line, col;

  if (!replace_dialog)
    return;

  QString to_find_string = replace_dialog->getText();

  int lineFrom, lineTo, colFrom, colTo;
  getSelection(&lineFrom, &colFrom, &lineTo, &colTo);

  // replace_dialog->get_direction() is true if searching backward
  if (replace_dialog->get_direction())
  {
    if (colFrom != -1)
    {
      col = colFrom - to_find_string.length();
      line = lineFrom;
    }
    else
    {
      getCursorPosition(&line,&col);
      col--;
    }
  }
  else
  {
    if (colTo != -1)
    {
      col = colTo;
      line = lineTo;
    }
    else
    {
      getCursorPosition(&line,&col);
    }
  }

again:

  int  result = doReplace(to_find_string, replace_dialog->case_sensitive(),
			 false, (!replace_dialog->get_direction()), line, col, false );

  if(!result){
    if(!replace_dialog->get_direction()){ // forward search

     int query = KMessageBox::questionYesNo(
			replace_dialog,
                        i18n("End of document reached.\n"\
                             "Continue from the beginning?"),
                        i18n("Replace"),KStdGuiItem::cont(),i18n("Stop"));
     if (query == KMessageBox::Yes){
	line = 0;
	col = 0;
	goto again;
      }
    }
    else{ //backward search

     int query = KMessageBox::questionYesNo(
			replace_dialog,
                        i18n("Beginning of document reached.\n"\
                             "Continue from the end?"),
                        i18n("Replace"),KStdGuiItem::cont(),i18n("Stop"));
      if (query == KMessageBox::Yes){
	QString string = textLine( numLines() - 1 );
	line = numLines() - 1;
	col  = string.length();
	last_replace = BACKWARD;
	goto again;
      }
    }
  }
  else{

    emit CursorPositionChanged();
  }
}
Example #25
0
/* antlarr: KDE 4: make it const QString & */
int KEdit::doSearch(QString s_pattern, bool case_sensitive,
		    bool wildcard, bool forward, int line, int col){

  (void) wildcard; // reserved for possible extension to regex


  int i, length;
  int pos = -1;

  if(forward){

    QString string;

    for(i = line; i < numLines(); i++) {

      string = textLine(i);

      pos = string.find(s_pattern, i == line ? col : 0, case_sensitive);

      if( pos != -1){

	length = s_pattern.length();

	setCursorPosition(i,pos,false);

	for(int l = 0 ; l < length; l++){
	  cursorRight(true);
	}

	setCursorPosition( i , pos + length, true );
	pattern = s_pattern;
	last_search = FORWARD;

	return 1;
      }
    }
  }
  else{ // searching backwards

    QString string;

    for(i = line; i >= 0; i--) {

      string = textLine(i);
      int line_length = string.length();

      pos = string.findRev(s_pattern, line == i ? col : line_length , case_sensitive);

      if (pos != -1){

	length = s_pattern.length();

	if( ! (line == i && pos > col ) ){

	  setCursorPosition(i ,pos ,false );

	  for(int l = 0 ; l < length; l++){
	    cursorRight(true);
	  }

	  setCursorPosition(i ,pos + length ,true );
	  pattern = s_pattern;
	  last_search = BACKWARD;
	  return 1;

	}
      }

    }
  }

  return 0;

}