calamares/src/libcalamaresui/widgets/LogWidget.cpp

103 lines
2.1 KiB
C++
Raw Normal View History

2022-03-06 14:45:48 +01:00
#include "LogWidget.h"
#include "utils/Logger.h"
#include <QFile>
#include <QStackedLayout>
2022-03-06 14:45:48 +01:00
#include <QTextStream>
#include <QThread>
namespace Calamares
{
LogThread::LogThread( QObject* parent )
: QThread( parent )
{
2022-03-06 14:45:48 +01:00
}
2022-03-10 20:33:22 +01:00
LogThread::~LogThread()
{
quit();
requestInterruption();
wait();
}
void
LogThread::run()
2022-03-06 14:45:48 +01:00
{
const auto filePath = Logger::logFile();
2022-03-06 14:45:48 +01:00
qint64 lastPosition = 0;
while ( !QThread::currentThread()->isInterruptionRequested() )
{
QFile file( filePath );
2022-03-06 14:45:48 +01:00
qint64 fileSize = file.size();
// Check whether the file size has changed since last time
// we read the file.
if ( lastPosition != fileSize && file.open( QFile::ReadOnly | QFile::Text ) )
{
2022-03-06 14:45:48 +01:00
// Start reading at the position we ended up last time we read the file.
file.seek( lastPosition );
2022-03-06 14:45:48 +01:00
QTextStream in( &file );
2022-03-06 14:45:48 +01:00
auto chunk = in.readAll();
qint64 newPosition = in.pos();
lastPosition = newPosition;
Q_EMIT onLogChunk( chunk );
2022-03-06 14:45:48 +01:00
}
QThread::msleep( 100 );
2022-03-06 14:45:48 +01:00
}
}
LogWidget::LogWidget( QWidget* parent )
: QWidget( parent )
2022-03-06 14:45:48 +01:00
, m_text( new QPlainTextEdit )
, m_log_thread( this )
{
auto layout = new QStackedLayout( this );
setLayout( layout );
2022-03-06 14:45:48 +01:00
m_text->setReadOnly( true );
2022-03-06 14:45:48 +01:00
QFont monospaceFont( "monospace" );
monospaceFont.setStyleHint( QFont::Monospace );
m_text->setFont( monospaceFont );
2022-03-06 14:45:48 +01:00
layout->addWidget( m_text );
2022-03-06 14:45:48 +01:00
connect( &m_log_thread, &LogThread::onLogChunk, this, &LogWidget::handleLogChunk );
2022-03-06 14:45:48 +01:00
m_log_thread.setPriority( QThread::LowestPriority );
2022-03-06 14:45:48 +01:00
m_log_thread.start();
}
void
LogWidget::handleLogChunk( const QString& logChunk )
2022-03-06 14:45:48 +01:00
{
m_text->appendPlainText( logChunk );
m_text->moveCursor( QTextCursor::End );
2022-03-06 14:45:48 +01:00
m_text->ensureCursorVisible();
}
void
LogWidget::start()
{
if ( !m_log_thread.isRunning() )
{
m_text->clear();
m_log_thread.start();
}
}
void
LogWidget::stop()
{
m_log_thread.requestInterruption();
}
} // namespace Calamares