fix astyle locale (v2) (#479)

This commit is contained in:
Cyano Hao 2024-09-03 19:53:15 +08:00 committed by GitHub
parent f043e02b13
commit 20cb728306
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
6 changed files with 85 additions and 42 deletions

View File

@ -56,6 +56,7 @@
#include <QDebug> #include <QDebug>
#include "project.h" #include "project.h"
#include <qt_utils/charsetinfo.h> #include <qt_utils/charsetinfo.h>
#include "utils/escape.h"
QHash<ParserLanguage,std::weak_ptr<CppParser>> Editor::mSharedParsers; QHash<ParserLanguage,std::weak_ptr<CppParser>> Editor::mSharedParsers;
@ -5115,17 +5116,34 @@ void Editor::reformat(bool doReparse)
{ {
if (readOnly()) if (readOnly())
return; return;
if (!fileExists(pSettings->environment().AStylePath())) { const QString &astyle = pSettings->environment().AStylePath();
if (!fileExists(astyle)) {
QMessageBox::critical(this, QMessageBox::critical(this,
tr("astyle not found"), tr("astyle not found"),
tr("Can't find astyle in \"%1\".").arg(pSettings->environment().AStylePath())); tr("Can't find astyle in \"%1\".").arg(astyle));
return; return;
} }
//we must remove all breakpoints and syntax issues //we must remove all breakpoints and syntax issues
// onLinesDeleted(1,lineCount()); // onLinesDeleted(1,lineCount());
QByteArray content = text().toUtf8(); QByteArray content = text().toUtf8();
QStringList args = pSettings->codeFormatter().getArguments(); QStringList args = pSettings->codeFormatter().getArguments();
QByteArray newContent = reformatContentUsingAstyle(content,args); QString command = escapeCommandForPlatformShell(extractFileName(astyle), args);
pMainWindow->logToolsOutput(tr("Reformatting content using astyle..."));
pMainWindow->logToolsOutput("------------------");
pMainWindow->logToolsOutput(tr("- Astyle: %1").arg(astyle));
pMainWindow->logToolsOutput(tr("- Command: %1").arg(command));
auto [newContent, astyleError, processError] =
runAndGetOutput(astyle, extractFileDir(astyle), args, content, true);
if (!astyleError.isEmpty()) {
#ifdef Q_OS_WIN
QString msg = QString::fromLocal8Bit(astyleError);
#else
QString msg = QString::fromUtf8(astyleError);
#endif
pMainWindow->logToolsOutput(msg);
}
if (!processError.isEmpty())
pMainWindow->logToolsOutput(processError);
if (newContent.isEmpty()) if (newContent.isEmpty())
return; return;
replaceContent(QString::fromUtf8(newContent), doReparse); replaceContent(QString::fromUtf8(newContent), doReparse);

View File

@ -1218,6 +1218,7 @@ void MainWindow::executeTool(PToolItem item)
Editor *e; Editor *e;
QByteArray inputContent; QByteArray inputContent;
QByteArray output; QByteArray output;
QString errorMessage;
clearToolsOutput(); clearToolsOutput();
switch(item->inputOrigin) { switch(item->inputOrigin) {
case ToolItemInputOrigin::None: case ToolItemInputOrigin::None:
@ -1251,18 +1252,24 @@ void MainWindow::executeTool(PToolItem item)
QString cmd="cmd"; QString cmd="cmd";
QStringList args{"/C",file.fileName()}; QStringList args{"/C",file.fileName()};
command = escapeCommandForPlatformShell(cmd, args); command = escapeCommandForPlatformShell(cmd, args);
output = runAndGetOutput(cmd, workDir, args, inputContent); auto [o, _, em] = runAndGetOutput(cmd, workDir, args, inputContent);
output = o;
errorMessage = em;
} }
} else { } else {
#endif #endif
command = escapeCommandForPlatformShell(program, params); command = escapeCommandForPlatformShell(program, params);
output = runAndGetOutput(program, workDir, params, inputContent); auto [o, _, em] = runAndGetOutput(program, workDir, params, inputContent);
output = o;
errorMessage = em;
#ifdef Q_OS_WIN #ifdef Q_OS_WIN
} }
#endif #endif
switch(item->outputTarget) { switch(item->outputTarget) {
case ToolItemOutputTarget::RedirectToToolsOutputPanel: case ToolItemOutputTarget::RedirectToToolsOutputPanel:
logToolsOutput(tr(" - Command: %1").arg(command)); logToolsOutput(tr(" - Command: %1").arg(command));
if (!errorMessage.isEmpty())
logToolsOutput(errorMessage);
logToolsOutput(""); logToolsOutput("");
logToolsOutput(byteArrayToString(output, item->isUTF8)); logToolsOutput(byteArrayToString(output, item->isUTF8));
stretchMessagesPanel(true); stretchMessagesPanel(true);
@ -1273,12 +1280,12 @@ void MainWindow::executeTool(PToolItem item)
case ToolItemOutputTarget::RepalceWholeDocument: case ToolItemOutputTarget::RepalceWholeDocument:
e=mEditorList->getEditor(); e=mEditorList->getEditor();
if (e) if (e)
e->replaceContent(byteArrayToString(output, item->isUTF8)); e->replaceContent(errorMessage + byteArrayToString(output, item->isUTF8));
break; break;
case ToolItemOutputTarget::ReplaceCurrentSelection: case ToolItemOutputTarget::ReplaceCurrentSelection:
e=mEditorList->getEditor(); e=mEditorList->getEditor();
if (e) if (e)
e->setSelText(byteArrayToString(output, item->isUTF8)); e->setSelText(errorMessage + byteArrayToString(output, item->isUTF8));
break; break;
} }
} }

View File

@ -2849,12 +2849,13 @@ QByteArray Settings::CompilerSet::getCompilerOutput(const QString &binDir, const
env.insert("LANG","en"); env.insert("LANG","en");
QString path = binDir; QString path = binDir;
env.insert("PATH",path); env.insert("PATH",path);
QByteArray result = runAndGetOutput( auto [result, _, errorMessage] = runAndGetOutput(
includeTrailingPathDelimiter(binDir)+binFile, includeTrailingPathDelimiter(binDir)+binFile,
binDir, binDir,
arguments, arguments,
QByteArray(), QByteArray(),
false, false,
false,
env); env);
return result.trimmed(); return result.trimmed();
} }

View File

@ -326,8 +326,9 @@ void FormatterGeneralWidget::on_chkBreakMaxCodeLength_stateChanged(int)
void FormatterGeneralWidget::updateDemo() void FormatterGeneralWidget::updateDemo()
{ {
if (!fileExists(pSettings->environment().AStylePath())) { const QString &astyle = pSettings->environment().AStylePath();
ui->editDemo->document()->setText(Editor::tr("Can't find astyle in \"%1\".").arg(pSettings->environment().AStylePath())); if (!fileExists(astyle)) {
ui->editDemo->document()->setText(Editor::tr("Can't find astyle in \"%1\".").arg(astyle));
return; return;
} }
QFile file(":/codes/formatdemo.cpp"); QFile file(":/codes/formatdemo.cpp");
@ -337,8 +338,20 @@ void FormatterGeneralWidget::updateDemo()
Settings::CodeFormatter formatter(nullptr); Settings::CodeFormatter formatter(nullptr);
updateCodeFormatter(formatter); updateCodeFormatter(formatter);
QByteArray newContent = reformatContentUsingAstyle(content, formatter.getArguments()); auto [newContent, astyleError, processError] =
ui->editDemo->document()->setText(newContent); runAndGetOutput(astyle, extractFileDir(astyle), formatter.getArguments(), content, true);
QString display;
if (!processError.isEmpty())
display += processError + '\n';
if (!astyleError.isEmpty()) {
#ifdef Q_OS_WIN
display += QString::fromLocal8Bit(astyleError) + '\n';
#else
display += QString::fromUtf8(astyleError) + '\n';
#endif
}
display += newContent;
ui->editDemo->document()->setText(display);
} }
void FormatterGeneralWidget::updateCodeFormatter(Settings::CodeFormatter &format) void FormatterGeneralWidget::updateCodeFormatter(Settings::CodeFormatter &format)

View File

@ -369,12 +369,16 @@ bool isGreenEdition()
} }
#endif #endif
QByteArray runAndGetOutput(const QString &cmd, const QString& workingDir, const QStringList& arguments, ProcessOutput runAndGetOutput(const QString &cmd, const QString& workingDir, const QStringList& arguments,
const QByteArray &inputContent, bool inheritEnvironment, const QByteArray &inputContent,
bool separateStderr,
bool inheritEnvironment,
const QProcessEnvironment& env) const QProcessEnvironment& env)
{ {
QProcess process; QProcess process;
QByteArray result; QByteArray standardOutput;
QByteArray standardError;
QString errorMessage;
bool errorOccurred = false; bool errorOccurred = false;
if (env.isEmpty()) { if (env.isEmpty()) {
if (inheritEnvironment) { if (inheritEnvironment) {
@ -385,12 +389,20 @@ QByteArray runAndGetOutput(const QString &cmd, const QString& workingDir, const
} else { } else {
process.setProcessEnvironment(env); process.setProcessEnvironment(env);
} }
if (separateStderr)
process.setProcessChannelMode(QProcess::SeparateChannels);
else
process.setProcessChannelMode(QProcess::MergedChannels); process.setProcessChannelMode(QProcess::MergedChannels);
process.setReadChannel(QProcess::StandardOutput); process.setReadChannel(QProcess::StandardOutput);
process.setWorkingDirectory(workingDir); process.setWorkingDirectory(workingDir);
process.connect(&process,&QProcess::readyReadStandardOutput, process.connect(&process,&QProcess::readyReadStandardOutput,
[&](){ [&](){
result.append(process.readAllStandardOutput()); standardOutput.append(process.readAllStandardOutput());
});
if (separateStderr)
process.connect(&process, &QProcess::readyReadStandardError,
[&]() {
standardError.append(process.readAllStandardError());
}); });
process.connect(&process, &QProcess::errorOccurred, process.connect(&process, &QProcess::errorOccurred,
[&](){ [&](){
@ -405,28 +417,27 @@ QByteArray runAndGetOutput(const QString &cmd, const QString& workingDir, const
if (errorOccurred) { if (errorOccurred) {
switch(process.error()) { switch(process.error()) {
case QProcess::FailedToStart: case QProcess::FailedToStart:
result += "Failed to start process!"; errorMessage += "Failed to start process!";
break; break;
case QProcess::Crashed: case QProcess::Crashed:
result += "Process crashed!"; errorMessage += "Process crashed!";
break; break;
case QProcess::Timedout: case QProcess::Timedout:
result += "Timeout!"; errorMessage += "Timeout!";
break; break;
case QProcess::ReadError: case QProcess::ReadError:
result += "Read Error:"; errorMessage += "Read Error:";
break; break;
case QProcess::WriteError: case QProcess::WriteError:
result += "Write Error:"; errorMessage += "Write Error:";
break; break;
case QProcess::UnknownError: case QProcess::UnknownError:
result += "Unknown Error:"; errorMessage += "Unknown Error:";
break; break;
} }
errorMessage += process.errorString();
//result += process.errorString().toLocal8Bit();
} }
return result; return {standardOutput, standardError, errorMessage};
} }
void executeFile(const QString &fileName, const QStringList &params, const QString &workingDir, const QString &tempFile) void executeFile(const QString &fileName, const QStringList &params, const QString &workingDir, const QString &tempFile)
@ -772,19 +783,6 @@ std::tuple<QString, QStringList, PNonExclusiveTemporaryFileOwner> wrapCommandFor
return wrapCommandForTerminalEmulator(terminal, parseArguments(argsPattern, Settings::Environment::terminalArgsPatternMagicVariables(), false), payloadArgsWithArgv0); return wrapCommandForTerminalEmulator(terminal, parseArguments(argsPattern, Settings::Environment::terminalArgsPatternMagicVariables(), false), payloadArgsWithArgv0);
} }
QByteArray reformatContentUsingAstyle(const QByteArray &content, const QStringList &arguments)
{
QProcessEnvironment env;
env.insert("LANG","en");
QByteArray newContent = runAndGetOutput(pSettings->environment().AStylePath(),
extractFileDir(pSettings->environment().AStylePath()),
arguments,
content,
false,
env);
return newContent;
}
ExternalResource::ExternalResource() { ExternalResource::ExternalResource() {
Q_INIT_RESOURCE(qsynedit_qmake_qmake_qm_files); Q_INIT_RESOURCE(qsynedit_qmake_qmake_qm_files);
Q_INIT_RESOURCE(redpanda_qt_utils_qmake_qmake_qm_files); Q_INIT_RESOURCE(redpanda_qt_utils_qmake_qmake_qm_files);

View File

@ -143,13 +143,19 @@ void resetCppParser(std::shared_ptr<CppParser> parser, int compilerSetIndex=-1);
int getNewFileNumber(); int getNewFileNumber();
QByteArray runAndGetOutput(const QString& cmd, const QString& workingDir, const QStringList& arguments, struct ProcessOutput
{
QByteArray standardOutput;
QByteArray standardError;
QString errorMessage;
};
ProcessOutput runAndGetOutput(const QString& cmd, const QString& workingDir, const QStringList& arguments,
const QByteArray& inputContent = QByteArray(), const QByteArray& inputContent = QByteArray(),
bool separateStderr = false,
bool inheritEnvironment = false, bool inheritEnvironment = false,
const QProcessEnvironment& env = QProcessEnvironment() ); const QProcessEnvironment& env = QProcessEnvironment() );
QByteArray reformatContentUsingAstyle(const QByteArray& content, const QStringList& arguments);
void openFileFolderInExplorer(const QString& path); void openFileFolderInExplorer(const QString& path);
void executeFile(const QString& fileName, void executeFile(const QString& fileName,