105 lines
2.5 KiB
C++
105 lines
2.5 KiB
C++
#include "consolemanager.hpp"
|
||
#include <QRegularExpression>
|
||
|
||
namespace
|
||
{
|
||
constexpr int kMaxLogLines = 1000;
|
||
|
||
QString strip_ansi(const QString &text)
|
||
{
|
||
static const QRegularExpression ansi(QStringLiteral("\\x1b\\[[0-9;?]*[ -/]*[@-~]"));
|
||
QString result = text;
|
||
result.remove(ansi);
|
||
return result;
|
||
}
|
||
}
|
||
|
||
ConsoleManager::ConsoleManager(QObject* parent) : QObject{ parent }
|
||
{
|
||
// QML получает не каждую строку, а накопленную пачку: иначе ListView
|
||
// сбрасывается на каждой строке и GUI-поток блокируется на больших логах.
|
||
m_notify_timer.setSingleShot(true);
|
||
m_notify_timer.setInterval(100);
|
||
connect(&m_notify_timer, &QTimer::timeout, this, [this] {
|
||
m_notify_pending = false;
|
||
emit update_log_changed();
|
||
});
|
||
}
|
||
|
||
void ConsoleManager::set_package_manager(const QString& pm)
|
||
{
|
||
m_package_manager = pm;
|
||
}
|
||
|
||
QStringList ConsoleManager::update_log() const { return m_update_log; }
|
||
|
||
void ConsoleManager::append_update_log(const QByteArray& chunk)
|
||
{
|
||
const QString text = QString::fromUtf8(chunk);
|
||
|
||
for (const QChar ch : text)
|
||
{
|
||
if (ch == QLatin1Char('\r'))
|
||
{
|
||
m_pending_cr = true;
|
||
continue;
|
||
}
|
||
|
||
if (ch == QLatin1Char('\n'))
|
||
{
|
||
commit_line();
|
||
m_pending_cr = false;
|
||
continue;
|
||
}
|
||
|
||
if (m_pending_cr)
|
||
{
|
||
m_update_log_buffer.clear();
|
||
m_pending_cr = false;
|
||
}
|
||
|
||
m_update_log_buffer += ch;
|
||
}
|
||
}
|
||
|
||
void ConsoleManager::clear()
|
||
{
|
||
m_notify_timer.stop();
|
||
m_notify_pending = false;
|
||
m_update_log.clear();
|
||
m_update_log_buffer.clear();
|
||
m_pending_cr = false;
|
||
emit update_log_changed();
|
||
}
|
||
|
||
void ConsoleManager::add_log_line(const QString& line)
|
||
{
|
||
// недописанная строка вывода должна попасть в лог раньше новой строки
|
||
if (!m_update_log_buffer.isEmpty()) commit_line();
|
||
|
||
const QString clean = strip_ansi(line).trimmed();
|
||
if (clean.isEmpty()) return;
|
||
|
||
if (m_update_log.size() >= kMaxLogLines) m_update_log.removeFirst();
|
||
m_update_log.append(clean);
|
||
|
||
schedule_log_changed();
|
||
}
|
||
|
||
void ConsoleManager::schedule_log_changed()
|
||
{
|
||
if (m_notify_pending) return;
|
||
|
||
m_notify_pending = true;
|
||
m_notify_timer.start();
|
||
}
|
||
|
||
void ConsoleManager::commit_line()
|
||
{
|
||
const QString line = m_update_log_buffer;
|
||
m_update_log_buffer.clear();
|
||
m_pending_cr = false;
|
||
if (!line.trimmed().isEmpty())
|
||
add_log_line(m_package_manager + QStringLiteral(": ") + line);
|
||
}
|