Skip to content

Commit

Permalink
调整stdout的重定向,和临时log的读取方法
Browse files Browse the repository at this point in the history
  • Loading branch information
Elivicti committed Dec 19, 2024
1 parent fbdc5ab commit e14822c
Showing 1 changed file with 57 additions and 16 deletions.
73 changes: 57 additions & 16 deletions src/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,58 @@

#include "ErrorDialog.h"

struct ScopedRedirect
{
ScopedRedirect(const char* fname)
: og_stdout{ *stdout }
, launch_log{ std::freopen(fname, "w+", stderr) }
, log{ fname }
{}

~ScopedRedirect()
{
close_log();
remove();
}

void close_log()
{
std::fclose(launch_log);
if (!log.isOpen())
log.open(QIODevice::ReadOnly);
*stdout = og_stdout;
}

QString read_all()
{
if (!log.isOpen())
{
return log.errorString();
}
return log.readAll();
}

void remove()
{
if (log.remove())
return;
close_log();
log.remove();
}

QString read_and_close()
{
close_log();
QString content = read_all();
remove();
return content;
}

std::FILE og_stdout;
std::FILE* launch_log;
QFile log;
};

int main(int argc, char *argv[])
{
QApplication app{ argc,argv };
Expand All @@ -21,34 +73,23 @@ int main(int argc, char *argv[])
// do not set to application path if in debug mode
QDir::setCurrent(app.applicationDirPath());

auto old_stdout = *stderr;
auto p = std::freopen("launch.log", "w+", stderr);
ScopedRedirect r{ "launch.log" };
#endif

try
{
pybind11::scoped_interpreter guard{};
PngPortrait2DDS w;
w.show();

#ifndef _DEBUG
r.remove();
#endif
return app.exec();
}
#ifndef _DEBUG
catch (const std::exception& e)
{
*stderr = old_stdout;
QFile temp{ "launch.log" };
if (!temp.open(QIODevice::ReadOnly))
{
qDebug() << "somehow failed: " << temp.errorString();
}

QString msg{ temp.readAll() };

if (!temp.remove())
{
qDebug() << "somehow failed: " << temp.errorString();
}
QString msg{ r.read_and_close() };

ErrorDialog msg_box{ QObject::tr("Critical Error"), msg += e.what() };
msg_box.setHelperText(QObject::tr(
Expand Down

0 comments on commit e14822c

Please sign in to comment.