Source

pynoto / src / Main / Consoles / ApplicationOutput.cpp

#include <QDebug>
#include <QScrollBar>
#include "ApplicationOutput.h"
#include "IApplicationOutput.h"

namespace Main {

ApplicationOutput::ApplicationOutput(QWidget *parent) :
    QPlainTextEdit(parent),
    _linksActive(false),
    _mousePressed(false)
{
    setReadOnly(true);
    _errFmt.setForeground(Qt::red);
    _normFmt.setForeground(Qt::black);
    _fileFind.setPattern(".*File \"(.+)?\", line (\\d+).*");
}

void ApplicationOutput::addOutput(const QString& line)
{
    addLine(line, _normFmt);
}

void ApplicationOutput::addError(const QString& line)
{
    addLine(line, _errFmt);
}

void ApplicationOutput::addLine(const QString& line, const QTextCharFormat& format)
{
    _mut.lock();
    QTextCursor cursor = textCursor();

    QString insertLine = line.endsWith("\n") ? line : line+"\n";

    moveCursor(QTextCursor::End);
    cursor.beginEditBlock();
    cursor.insertText(insertLine, format);
    int pos = 0;
    if ((pos = _fileFind.indexIn(line, pos)) != -1 ){
        QString file = _fileFind.cap(1);
        QString line = _fileFind.cap(2);
        qDebug() << pos;

        QList<QTextEdit::ExtraSelection> extra = extraSelections();
        QTextEdit::ExtraSelection sel;
        sel.format.setAnchorHref(file);
        sel.format.setAnchor(true);
        sel.format.setUnderlineStyle(QTextCharFormat::SingleUnderline);
        cursor.movePosition(QTextCursor::PreviousCharacter, QTextCursor::MoveAnchor, insertLine.length()-_fileFind.pos(1));
        cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor, file.length());
        sel.cursor = cursor;
        extra.append(sel);

        setExtraSelections(extra);
    }


    cursor.endEditBlock();
    scrollToBottom();
    _mut.unlock();
}

void ApplicationOutput::scrollToBottom()
{
    verticalScrollBar()->setValue(verticalScrollBar()->maximum());
    verticalScrollBar()->setValue(verticalScrollBar()->maximum());
}

void ApplicationOutput::mouseMoveEvent(QMouseEvent *e)
{
    if (_mousePressed && textCursor().hasSelection())
        _linksActive = false;

    if (!_linksActive || anchorAt(e->pos()).isEmpty())
        viewport()->setCursor(Qt::IBeamCursor);
    else
        viewport()->setCursor(Qt::PointingHandCursor);
    QPlainTextEdit::mouseMoveEvent(e);
}

void ApplicationOutput::mousePressEvent(QMouseEvent * e)
{
    _mousePressed = true;
    QPlainTextEdit::mousePressEvent(e);
}

void ApplicationOutput::mouseReleaseEvent(QMouseEvent *e)
{
    _mousePressed = false;

    if (_linksActive) {
        const QString href = anchorAt(e->pos());
        //if (m_formatter)
        //    m_formatter->handleLink(href);
    }

    _linksActive = true;

    QPlainTextEdit::mouseReleaseEvent(e);
}

}