Files
archpack/cpp/managers/consolemanager/consolemanager.cpp
2026-12-06 09:38:29 +03:00

105 lines
2.5 KiB
C++
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#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);
}