work save

This commit is contained in:
royqh1979@gmail.com 2021-11-12 10:51:00 +08:00
parent 88bb3b25cb
commit 8b7d19f94e
16 changed files with 204 additions and 88 deletions

View File

@ -25,6 +25,7 @@ SOURCES += \
compiler/ojproblemcasesrunner.cpp \ compiler/ojproblemcasesrunner.cpp \
compiler/projectcompiler.cpp \ compiler/projectcompiler.cpp \
compiler/runner.cpp \ compiler/runner.cpp \
gdbmiresultparser.cpp \
platform.cpp \ platform.cpp \
compiler/compiler.cpp \ compiler/compiler.cpp \
compiler/compilermanager.cpp \ compiler/compilermanager.cpp \
@ -154,6 +155,7 @@ HEADERS += \
compiler/runner.h \ compiler/runner.h \
compiler/stdincompiler.h \ compiler/stdincompiler.h \
cpprefacter.h \ cpprefacter.h \
gdbmiresultparser.h \
parser/cppparser.h \ parser/cppparser.h \
parser/cpppreprocessor.h \ parser/cpppreprocessor.h \
parser/cpptokenizer.h \ parser/cpptokenizer.h \

View File

@ -93,7 +93,7 @@ void ExecutableRunner::run()
process.start(); process.start();
process.waitForStarted(5000); process.waitForStarted(5000);
if (process.state()==QProcess::Running && redirectInput()) { if (process.state()==QProcess::Running && redirectInput()) {
process.write(ReadFileToByteArray(redirectInputFilename())); process.write(readFileToByteArray(redirectInputFilename()));
process.closeWriteChannel(); process.closeWriteChannel();
} }
while (true) { while (true) {

View File

@ -15,6 +15,7 @@
#include <QJsonArray> #include <QJsonArray>
#include <QJsonObject> #include <QJsonObject>
#include <QJsonDocument> #include <QJsonDocument>
#include <QJsonDocument>
Debugger::Debugger(QObject *parent) : QObject(parent) Debugger::Debugger(QObject *parent) : QObject(parent)
{ {
@ -485,7 +486,7 @@ void Debugger::syncFinishedParsing()
pMainWindow->addDebugOutput(""); pMainWindow->addDebugOutput("");
pMainWindow->addDebugOutput(""); pMainWindow->addDebugOutput("");
} else { } else {
QStringList strList = TextToLines(mReader->mOutput); QStringList strList = textToLines(mReader->mOutput);
QStringList outStrList; QStringList outStrList;
bool addToLastLine=false; bool addToLastLine=false;
for (int i=0;i<strList.size();i++) { for (int i=0;i<strList.size();i++) {
@ -774,7 +775,7 @@ AnnotationType DebugReader::getNextAnnotation()
bool DebugReader::outputTerminated(QByteArray &text) bool DebugReader::outputTerminated(QByteArray &text)
{ {
QStringList lines = TextToLines(QString::fromUtf8(text)); QStringList lines = textToLines(QString::fromUtf8(text));
foreach (const QString& line,lines) { foreach (const QString& line,lines) {
if (line == "(gdb)") if (line == "(gdb)")
return true; return true;
@ -993,7 +994,7 @@ void DebugReader::handleLocalOutput()
QString line; QString line;
while (true) { while (true) {
if (!s.startsWith("\032\032")) { if (!s.startsWith("\032\032")) {
s = TrimLeft(s); s = trimLeft(s);
if (s == "No locals.") { if (s == "No locals.") {
return; return;
} }
@ -1067,7 +1068,7 @@ void DebugReader::handleRegisters()
reg->name = s.mid(0,x); reg->name = s.mid(0,x);
s.remove(0,x); s.remove(0,x);
// Remove spaces // Remove spaces
s = TrimLeft(s); s = trimLeft(s);
// Cut hex value from 1 to first tab // Cut hex value from 1 to first tab
x = s.indexOf('\t'); x = s.indexOf('\t');
@ -1075,7 +1076,7 @@ void DebugReader::handleRegisters()
x = s.indexOf(' '); x = s.indexOf(' ');
reg->hexValue = s.mid(0,x); reg->hexValue = s.mid(0,x);
s.remove(0,x); // delete tab too s.remove(0,x); // delete tab too
s = TrimLeft(s); s = trimLeft(s);
// Remaining part contains decimal value // Remaining part contains decimal value
reg->decValue = s; reg->decValue = s;
@ -1120,7 +1121,7 @@ void DebugReader::handleSignal()
void DebugReader::handleSource() void DebugReader::handleSource()
{ {
// source filename:line:offset:beg/middle/end:addr // source filename:line:offset:beg/middle/end:addr
QString s = TrimLeft(getRemainingLine()); QString s = trimLeft(getRemainingLine());
// remove offset, beg/middle/end, address // remove offset, beg/middle/end, address
for (int i=0;i<3;i++) { for (int i=0;i<3;i++) {
@ -1151,18 +1152,18 @@ void DebugReader::handleValueHistoryValue()
doevalready = true; doevalready = true;
} }
void DebugReader::processConsoleOutput(const QString& line) void DebugReader::processConsoleOutput(const QByteArray& line)
{ {
if (line.length()>3 && line.startsWith("~\"") && line.endsWith("\"")) { if (line.length()>3 && line.startsWith("~\"") && line.endsWith("\"")) {
mConsoleOutput.append(line.mid(2,line.length()-3)); mConsoleOutput.append(QString::fromLocal8Bit(line.mid(2,line.length()-3)));
} }
} }
void DebugReader::processResult(const QString &result) void DebugReader::processResult(const QByteArray &result)
{ {
int pos = result.indexOf('='); int pos = result.indexOf('=');
QString name = result.mid(0,pos); QByteArray name = result.mid(0,pos);
QString value = result.mid(pos+1); QByteArray value = result.mid(pos+1);
if (name == "bkpt") { if (name == "bkpt") {
// info about breakpoint // info about breakpoint
handleBreakpoint(value); handleBreakpoint(value);
@ -1220,12 +1221,12 @@ void DebugReader::processExecAsyncRecord(const QString &line)
} }
} }
void DebugReader::processError(const QString &errorLine) void DebugReader::processError(const QByteArray &errorLine)
{ {
//todo mConsoleOutput.append(QString::fromLocal8Bit(errorLine));
} }
void DebugReader::processResultRecord(const QString &line) void DebugReader::processResultRecord(const QByteArray &line)
{ {
if (line.startsWith("^exit")) { if (line.startsWith("^exit")) {
mProcessExited = true; mProcessExited = true;
@ -1239,7 +1240,7 @@ void DebugReader::processResultRecord(const QString &line)
|| line.startsWith("^running")) { || line.startsWith("^running")) {
int pos = line.indexOf(','); int pos = line.indexOf(',');
if (pos>=0) { if (pos>=0) {
QString result = line.mid(pos+1); QByteArray result = line.mid(pos+1);
processResult(result); processResult(result);
} }
return ; return ;
@ -1250,7 +1251,7 @@ void DebugReader::processResultRecord(const QString &line)
} }
} }
void DebugReader::processDebugOutput(const QString& debugOutput) void DebugReader::processDebugOutput(const QByteArray& debugOutput)
{ {
// Only update once per update at most // Only update once per update at most
//WatchView.Items.BeginUpdate; //WatchView.Items.BeginUpdate;
@ -1278,15 +1279,15 @@ void DebugReader::processDebugOutput(const QString& debugOutput)
doupdatecpuwindow = false; doupdatecpuwindow = false;
doreceivedsfwarning = false; doreceivedsfwarning = false;
QStringList lines = TextToLines(debugOutput); QList<QByteArray> lines = splitByteArrayToLines(debugOutput);
for (int i=0;i<lines.count();i++) { for (int i=0;i<lines.count();i++) {
QString line = lines[i]; QByteArray line = lines[i];
line = removeToken(line); line = removeToken(line);
if (line.isEmpty()) { if (line.isEmpty()) {
continue; continue;
} }
switch (line[0].unicode()) { switch (line[0]) {
case '~': // console stream output case '~': // console stream output
processConsoleOutput(line); processConsoleOutput(line);
break; break;
@ -1704,7 +1705,24 @@ QStringList DebugReader::tokenize(const QString &s)
return result; return result;
} }
QString DebugReader::removeToken(const QString &line) void DebugReader::handleBreakpoint(const QByteArray &breakpointRecord)
{
//we have to convert record from local encoding to utf8
//because QJsonDocument only handle utf8-encoded json strings
QString temp = QString::fromLocal8Bit(breakpointRecord);
QByteArray record = temp.toUtf8();
QJsonParseError error;
QJsonDocument doc = QJsonDocument::fromJson(record,&error);
if (error.error!=QJsonParseError::NoError) {
mConsoleOutput.append(QString("Error when parsing breakpoint record \"%1\":").arg(temp));
mConsoleOutput.append(error.errorString());
return;
}
QJsonObject obj = doc.object();
}
QByteArray DebugReader::removeToken(const QByteArray &line)
{ {
int p=0; int p=0;
while (p<line.length()) { while (p<line.length()) {
@ -1825,7 +1843,7 @@ void DebugReader::run()
if ( readed.endsWith("\r\n")&& outputTerminated(buffer)) { if ( readed.endsWith("\r\n")&& outputTerminated(buffer)) {
processDebugOutput(QString::fromLocal8Bit(buffer)); processDebugOutput(buffer);
buffer.clear(); buffer.clear();
mCmdRunning = false; mCmdRunning = false;
runNextCmd(); runNextCmd();

View File

@ -39,6 +39,9 @@ struct WatchVar {
}; };
struct Breakpoint { struct Breakpoint {
int number; // breakpoint number
QString type; // type of the breakpoint
QString catch_type;
int line; int line;
QString filename; QString filename;
QString condition; QString condition;
@ -301,19 +304,20 @@ private:
void handleSource(); void handleSource();
void handleValueHistoryValue(); void handleValueHistoryValue();
void processConsoleOutput(const QString& line);
void processResult(const QString& result);
void processExecAsyncRecord(const QString& line);
void processError(const QString& errorLine);
void processResultRecord(const QString& line);
void processDebugOutput(const QString& debugOutput);
QString processEvalOutput(); QString processEvalOutput();
void processWatchOutput(PWatchVar WatchVar); void processWatchOutput(PWatchVar WatchVar);
void runNextCmd(); void runNextCmd();
void skipSpaces();
void skipToAnnotation();
QStringList tokenize(const QString& s); QStringList tokenize(const QString& s);
QString removeToken(const QString& line);
void handleBreakpoint(const QByteArray& breakpointRecord);
void processConsoleOutput(const QByteArray& line);
void processResult(const QByteArray& result);
void processExecAsyncRecord(const QByteArray& line);
void processError(const QByteArray& errorLine);
void processResultRecord(const QByteArray& line);
void processDebugOutput(const QByteArray& debugOutput);
QByteArray removeToken(const QByteArray& line);
private: private:
Debugger *mDebugger; Debugger *mDebugger;
QString mDebuggerPath; QString mDebuggerPath;

View File

@ -602,12 +602,12 @@ void Editor::keyPressEvent(QKeyEvent *event)
insertString.append(QString(" * ")+USER_CODE_IN_INSERT_POS); insertString.append(QString(" * ")+USER_CODE_IN_INSERT_POS);
insertString.append(" */"); insertString.append(" */");
} }
insertCodeSnippet(LinesToText(insertString)); insertCodeSnippet(linesToText(insertString));
} else if (highlighter() } else if (highlighter()
&& caretY()>=2 && caretY()>=2
&& highlighter()->isLastLineCommentNotFinished( && highlighter()->isLastLineCommentNotFinished(
lines()->ranges(caretY()-2).state)) { lines()->ranges(caretY()-2).state)) {
s=TrimLeft(lineText()); s=trimLeft(lineText());
if (s.startsWith("* ")) { if (s.startsWith("* ")) {
handled = true; handled = true;
int right = lines()->getString(caretY()-1).length()-caretX(); int right = lines()->getString(caretY()-1).length()-caretX();
@ -2095,7 +2095,7 @@ void Editor::insertCodeSnippet(const QString &code)
auto action = finally([this]{ auto action = finally([this]{
endUpdate(); endUpdate();
}); });
QStringList sl = TextToLines(parseMacros(code)); QStringList sl = textToLines(parseMacros(code));
int lastI=0; int lastI=0;
int spaceCount = GetLeftSpacing( int spaceCount = GetLeftSpacing(
leftSpaces(lineText()),true).length(); leftSpaces(lineText()),true).length();
@ -2149,7 +2149,7 @@ void Editor::insertCodeSnippet(const QString &code)
} }
BufferCoord cursorPos = caretXY(); BufferCoord cursorPos = caretXY();
QString s = LinesToText(newSl); QString s = linesToText(newSl);
// if EndsStr(#13#10,s) then // if EndsStr(#13#10,s) then
// Delete(s,Length(s)-1,2) // Delete(s,Length(s)-1,2)
// else if EndsStr(#10, s) then // else if EndsStr(#10, s) then

View File

@ -0,0 +1,14 @@
#include "gdbmiresultparser.h"
#include <QList>
GDBMIResultParser::GDBMIResultParser()
{
}
bool GDBMIResultParser::parse(const QByteArray &record, GDBMIResultType &type, void **pResult)
{
QList<QByteArray> tokens;
tokens = tokenize(record);
}

View File

@ -0,0 +1,39 @@
#ifndef GDBMIRESULTPARSER_H
#define GDBMIRESULTPARSER_H
#include <QByteArray>
#include <QVariant>
enum class GDBMIResultType {
Breakpoint,
BreakpointTable,
FrameStack,
LocalVariables,
Locals,
Frame,
Disassembly,
Evaluation,
RegisterNames,
RegisterValues,
Memory
};
class GDBMIResultParser
{
struct ParseValue {
private:
QVariant mData;
};
struct ParseObject {
QHash<QByteArray, QVariant> props;
};
public:
GDBMIResultParser();
bool parse(const QByteArray& record, GDBMIResultType& type, void** pResult);
};
#endif // GDBMIRESULTPARSER_H

View File

@ -5099,8 +5099,8 @@ void MainWindow::updateProblemCaseOutput(POJProblemCase problemCase)
ui->txtProblemCaseOutput->clear(); ui->txtProblemCaseOutput->clear();
ui->txtProblemCaseOutput->setText(problemCase->output); ui->txtProblemCaseOutput->setText(problemCase->output);
if (problemCase->testState == ProblemCaseTestState::Failed) { if (problemCase->testState == ProblemCaseTestState::Failed) {
QStringList output = TextToLines(problemCase->output); QStringList output = textToLines(problemCase->output);
QStringList expected = TextToLines(problemCase->expected); QStringList expected = textToLines(problemCase->expected);
for (int i=0;i<output.count();i++) { for (int i=0;i<output.count();i++) {
if (i>=expected.count() || output[i]!=expected[i]) { if (i>=expected.count() || output[i]!=expected[i]) {
QTextBlock block = ui->txtProblemCaseOutput->document()->findBlockByLineNumber(i); QTextBlock block = ui->txtProblemCaseOutput->document()->findBlockByLineNumber(i);

View File

@ -680,7 +680,7 @@ void CppPreprocessor::openInclude(const QString &fileName, QStringList bufferedT
if (!bufferedText.isEmpty()) { if (!bufferedText.isEmpty()) {
parsedFile->buffer = bufferedText; parsedFile->buffer = bufferedText;
} else { } else {
parsedFile->buffer = ReadFileToLines(fileName); parsedFile->buffer = readFileToLines(fileName);
} }
} }
} else { } else {

View File

@ -10,8 +10,8 @@ bool ProblemCaseValidator::validate(POJProblemCase problemCase)
{ {
if (!problemCase) if (!problemCase)
return false; return false;
QStringList output = TextToLines(problemCase->output); QStringList output = textToLines(problemCase->output);
QStringList expected = TextToLines(problemCase->expected); QStringList expected = textToLines(problemCase->expected);
if (output.count()!=expected.count()) if (output.count()!=expected.count())
return false; return false;
for (int i=0;i<output.count();i++) { for (int i=0;i<output.count();i++) {

View File

@ -1020,7 +1020,7 @@ void Project::buildPrivateResource(bool forceSave)
rcFile = QDir(directory()).absoluteFilePath(rcFile); rcFile = QDir(directory()).absoluteFilePath(rcFile);
if (contents.count() > 3) { if (contents.count() > 3) {
StringsToFile(contents,rcFile); stringsToFile(contents,rcFile);
mOptions.privateResource = extractRelativePath(directory(), rcFile); mOptions.privateResource = extractRelativePath(directory(), rcFile);
} else { } else {
if (fileExists(rcFile)) if (fileExists(rcFile))
@ -1061,7 +1061,7 @@ void Project::buildPrivateResource(bool forceSave)
content.append(" </dependentAssembly>"); content.append(" </dependentAssembly>");
content.append("</dependency>"); content.append("</dependency>");
content.append("</assembly>"); content.append("</assembly>");
StringsToFile(content,executable() + ".Manifest"); stringsToFile(content,executable() + ".Manifest");
} else if (fileExists(executable() + ".Manifest")) } else if (fileExists(executable() + ".Manifest"))
QFile::remove(executable() + ".Manifest"); QFile::remove(executable() + ".Manifest");
@ -1107,7 +1107,7 @@ void Project::buildPrivateResource(bool forceSave)
.arg(mOptions.versionInfo.productVersion)); .arg(mOptions.versionInfo.productVersion));
contents.append(""); contents.append("");
contents.append("#endif /*" + def + "*/"); contents.append("#endif /*" + def + "*/");
StringsToFile(contents,hFile); stringsToFile(contents,hFile);
} }
void Project::checkProjectFileForUpdate(SimpleIni &ini) void Project::checkProjectFileForUpdate(SimpleIni &ini)
@ -1757,7 +1757,7 @@ bool ProjectUnit::save()
if (!mEditor && !fileExists(mFileName)) { if (!mEditor && !fileExists(mFileName)) {
// file is neither open, nor saved // file is neither open, nor saved
QStringList temp; QStringList temp;
StringsToFile(temp,mFileName); stringsToFile(temp,mFileName);
} else if (mEditor && mEditor->modified()) { } else if (mEditor && mEditor->modified()) {
result = mEditor->save(); result = mEditor->save();
} }

View File

@ -1785,7 +1785,7 @@ void SynEdit::doDeleteLastChar()
mLines->deleteAt(mCaretY); mLines->deleteAt(mCaretY);
doLinesDeleted(mCaretY+1, 1); doLinesDeleted(mCaretY+1, 1);
if (mOptions.testFlag(eoTrimTrailingSpaces)) if (mOptions.testFlag(eoTrimTrailingSpaces))
Temp = TrimRight(Temp); Temp = trimRight(Temp);
setLineText(lineText() + Temp); setLineText(lineText() + Temp);
helper = lineBreak(); //"/r/n" helper = lineBreak(); //"/r/n"
} }
@ -2119,7 +2119,7 @@ void SynEdit::insertLine(bool moveCaret)
rightLineText,mOptions.testFlag(eoAutoIndent) rightLineText,mOptions.testFlag(eoAutoIndent)
&& notInComment); && notInComment);
if (mOptions.testFlag(eoAutoIndent)) { if (mOptions.testFlag(eoAutoIndent)) {
rightLineText=TrimLeft(rightLineText); rightLineText=trimLeft(rightLineText);
} }
QString indentSpacesForRightLineText = GetLeftSpacing(indentSpaces,true); QString indentSpacesForRightLineText = GetLeftSpacing(indentSpaces,true);
mLines->insert(mCaretY, indentSpacesForRightLineText+rightLineText); mLines->insert(mCaretY, indentSpacesForRightLineText+rightLineText);
@ -2632,7 +2632,7 @@ void SynEdit::doAddChar(QChar AChar)
if (line.length() < oldCaretX) { if (line.length() < oldCaretX) {
int indentSpaces = calcIndentSpaces(oldCaretY,line+":", true); int indentSpaces = calcIndentSpaces(oldCaretY,line+":", true);
if (indentSpaces != leftSpaces(line)) { if (indentSpaces != leftSpaces(line)) {
QString temp = GetLeftSpacing(indentSpaces,true) + TrimLeft(line); QString temp = GetLeftSpacing(indentSpaces,true) + trimLeft(line);
int i = temp.length(); int i = temp.length();
mLines->putString(oldCaretY-1,temp); mLines->putString(oldCaretY-1,temp);
internalSetCaretXY(BufferCoord{i+1,oldCaretY}); internalSetCaretXY(BufferCoord{i+1,oldCaretY});
@ -4941,7 +4941,7 @@ void SynEdit::doLinesInserted(int firstLine, int count)
void SynEdit::properSetLine(int ALine, const QString &ALineText) void SynEdit::properSetLine(int ALine, const QString &ALineText)
{ {
if (mOptions.testFlag(eoTrimTrailingSpaces)) if (mOptions.testFlag(eoTrimTrailingSpaces))
mLines->putString(ALine,TrimRight(ALineText)); mLines->putString(ALine,trimRight(ALineText));
else else
mLines->putString(ALine,ALineText); mLines->putString(ALine,ALineText);
} }
@ -5047,7 +5047,7 @@ int SynEdit::insertTextByNormalMode(const QString &Value)
int Result = 0; int Result = 0;
sLeftSide = lineText().mid(0, mCaretX - 1); sLeftSide = lineText().mid(0, mCaretX - 1);
if (mCaretX - 1 > sLeftSide.length()) { if (mCaretX - 1 > sLeftSide.length()) {
if (StringIsBlank(sLeftSide)) if (stringIsBlank(sLeftSide))
sLeftSide = GetLeftSpacing(displayX() - 1, true); sLeftSide = GetLeftSpacing(displayX() - 1, true);
else else
sLeftSide += QString(mCaretX - 1 - sLeftSide.length(),' '); sLeftSide += QString(mCaretX - 1 - sLeftSide.length(),' ');
@ -5063,7 +5063,7 @@ int SynEdit::insertTextByNormalMode(const QString &Value)
Start = 0; Start = 0;
P = GetEOL(Value,Start); P = GetEOL(Value,Start);
if (P<Value.length()) { if (P<Value.length()) {
QString s = TrimLeft(Value.mid(0, P - Start)); QString s = trimLeft(Value.mid(0, P - Start));
if (sLeftSide.isEmpty()) { if (sLeftSide.isEmpty()) {
sLeftSide = GetLeftSpacing(calcIndentSpaces(caretY,s,true),true); sLeftSide = GetLeftSpacing(calcIndentSpaces(caretY,s,true),true);
} }
@ -5096,7 +5096,7 @@ int SynEdit::insertTextByNormalMode(const QString &Value)
Str += sRightSide; Str += sRightSide;
if (mOptions.testFlag(eoAutoIndent)) { if (mOptions.testFlag(eoAutoIndent)) {
int indentSpaces = calcIndentSpaces(caretY,Str,true); int indentSpaces = calcIndentSpaces(caretY,Str,true);
Str = GetLeftSpacing(indentSpaces,true)+TrimLeft(Str); Str = GetLeftSpacing(indentSpaces,true)+trimLeft(Str);
} }
} }
properSetLine(caretY - 1, Str); properSetLine(caretY - 1, Str);

View File

@ -492,7 +492,7 @@ void SynEditStringList::insertText(int Index, const QString &NewText)
} }
if (NewText.isEmpty()) if (NewText.isEmpty())
return; return;
QStringList lines = TextToLines(NewText); QStringList lines = textToLines(NewText);
insertStrings(Index,lines); insertStrings(Index,lines);
} }
@ -539,14 +539,14 @@ void SynEditStringList::loadFromFile(const QString& filename, const QByteArray&
allAscii = isTextAllAscii(line); allAscii = isTextAllAscii(line);
} }
if (allAscii) { if (allAscii) {
addItem(TrimRight(QString::fromLatin1(line))); addItem(trimRight(QString::fromLatin1(line)));
} else { } else {
QString newLine = codec->toUnicode(line.constData(),line.length(),&state); QString newLine = codec->toUnicode(line.constData(),line.length(),&state);
if (state.invalidChars>0) { if (state.invalidChars>0) {
needReread = true; needReread = true;
break; break;
} }
addItem(TrimRight(newLine)); addItem(trimRight(newLine));
} }
if (file.atEnd()){ if (file.atEnd()){
break; break;
@ -579,7 +579,7 @@ void SynEditStringList::loadFromFile(const QString& filename, const QByteArray&
QString line; QString line;
internalClear(); internalClear();
while (textStream.readLineInto(&line)) { while (textStream.readLineInto(&line)) {
addItem(TrimRight(line)); addItem(trimRight(line));
} }
emit inserted(0,mList.count()); emit inserted(0,mList.count());
} }

View File

@ -291,25 +291,25 @@ QString toLocalPath(const QString &filename)
return newPath; return newPath;
} }
QStringList TextToLines(const QString &text) QStringList textToLines(const QString &text)
{ {
QTextStream stream(&((QString&)text),QIODevice::ReadOnly); QTextStream stream(&((QString&)text),QIODevice::ReadOnly);
return ReadStreamToLines(&stream); return readStreamToLines(&stream);
} }
QStringList ReadFileToLines(const QString& fileName, QTextCodec* codec) QStringList readFileToLines(const QString& fileName, QTextCodec* codec)
{ {
QFile file(fileName); QFile file(fileName);
if (file.open(QFile::ReadOnly)) { if (file.open(QFile::ReadOnly)) {
QTextStream stream(&file); QTextStream stream(&file);
stream.setCodec(codec); stream.setCodec(codec);
stream.setAutoDetectUnicode(false); stream.setAutoDetectUnicode(false);
return ReadStreamToLines(&stream); return readStreamToLines(&stream);
} }
return QStringList(); return QStringList();
} }
QStringList ReadStreamToLines(QTextStream *stream) QStringList readStreamToLines(QTextStream *stream)
{ {
QStringList list; QStringList list;
QString s; QString s;
@ -319,7 +319,7 @@ QStringList ReadStreamToLines(QTextStream *stream)
return list; return list;
} }
void ReadStreamToLines(QTextStream *stream, void readStreamToLines(QTextStream *stream,
LineProcessFunc lineFunc) LineProcessFunc lineFunc)
{ {
QString s; QString s;
@ -328,20 +328,20 @@ void ReadStreamToLines(QTextStream *stream,
} }
} }
void TextToLines(const QString &text, LineProcessFunc lineFunc) void textToLines(const QString &text, LineProcessFunc lineFunc)
{ {
QTextStream stream(&((QString&)text),QIODevice::ReadOnly); QTextStream stream(&((QString&)text),QIODevice::ReadOnly);
ReadStreamToLines(&stream,lineFunc); readStreamToLines(&stream,lineFunc);
} }
void ReadFileToLines(const QString &fileName, QTextCodec *codec, LineProcessFunc lineFunc) void readFileToLines(const QString &fileName, QTextCodec *codec, LineProcessFunc lineFunc)
{ {
QFile file(fileName); QFile file(fileName);
if (file.open(QFile::ReadOnly)) { if (file.open(QFile::ReadOnly)) {
QTextStream stream(&file); QTextStream stream(&file);
stream.setCodec(codec); stream.setCodec(codec);
stream.setAutoDetectUnicode(false); stream.setAutoDetectUnicode(false);
ReadStreamToLines(&stream, lineFunc); readStreamToLines(&stream, lineFunc);
} }
} }
@ -401,7 +401,7 @@ void inflateRect(QRect &rect, int dx, int dy)
rect.setBottom(rect.bottom()+dy); rect.setBottom(rect.bottom()+dy);
} }
QString TrimRight(const QString &s) QString trimRight(const QString &s)
{ {
if (s.isEmpty()) if (s.isEmpty())
return s; return s;
@ -417,7 +417,7 @@ QString TrimRight(const QString &s)
} }
} }
bool StringIsBlank(const QString &s) bool stringIsBlank(const QString &s)
{ {
for (QChar ch:s) { for (QChar ch:s) {
if (ch != ' ' && ch != '\t') if (ch != ' ' && ch != '\t')
@ -426,7 +426,7 @@ bool StringIsBlank(const QString &s)
return true; return true;
} }
QString TrimLeft(const QString &s) QString trimLeft(const QString &s)
{ {
if (s.isEmpty()) if (s.isEmpty())
return s; return s;
@ -502,7 +502,7 @@ QString changeFileExt(const QString& filename, QString ext)
} }
} }
QStringList ReadFileToLines(const QString &fileName) QStringList readFileToLines(const QString &fileName)
{ {
QFile file(fileName); QFile file(fileName);
if (file.size()<=0) if (file.size()<=0)
@ -539,7 +539,7 @@ QStringList ReadFileToLines(const QString &fileName)
return result; return result;
} }
void StringsToFile(const QStringList &list, const QString &fileName) void stringsToFile(const QStringList &list, const QString &fileName)
{ {
QFile file(fileName); QFile file(fileName);
if (file.open(QIODevice::WriteOnly | QIODevice::Truncate)) { if (file.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
@ -748,7 +748,7 @@ QString fromByteArray(const QByteArray &s)
return QString::fromLocal8Bit(s); return QString::fromLocal8Bit(s);
} }
QString LinesToText(const QStringList &lines) QString linesToText(const QStringList &lines)
{ {
return lines.join("\n"); return lines.join("\n");
} }
@ -831,7 +831,7 @@ void executeFile(const QString &fileName, const QString &params, const QString &
); );
} }
void StringToFile(const QString &str, const QString &fileName) void stringToFile(const QString &str, const QString &fileName)
{ {
QFile file(fileName); QFile file(fileName);
if (file.open(QIODevice::WriteOnly | QIODevice::Truncate)) { if (file.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
@ -846,7 +846,7 @@ bool removeFile(const QString &filename)
return file.remove(); return file.remove();
} }
QByteArray ReadFileToByteArray(const QString &fileName) QByteArray readFileToByteArray(const QString &fileName)
{ {
QFile file(fileName); QFile file(fileName);
if (file.open(QFile::ReadOnly)) { if (file.open(QFile::ReadOnly)) {
@ -893,3 +893,40 @@ bool readRegistry(HKEY key,const QByteArray& subKey, const QByteArray& name, QSt
delete [] buffer; delete [] buffer;
return true; return true;
} }
QList<QByteArray> splitByteArrayToLines(const QByteArray &content)
{
QList<QByteArray> lines;
const char* p =content.constData();
const char* end = p+content.length();
const char* lineStart = p;
QByteArray line;
while (p<=end) {
char ch=*p;
switch(ch) {
case '\r':
line = QByteArray(lineStart, p-lineStart);
lines.append(line);
p++;
if (*p=='\n')
p++;
lineStart = p;
break;
case '\n':
line = QByteArray(lineStart, p-lineStart);
lines.append(line);
p++;
lineStart = p;
break;
default:
p++;
}
}
if (lineStart>end) {
lines.append("");
} else {
line = QByteArray(lineStart, end-lineStart+1);
lines.append(line);
}
return lines;
}

View File

@ -143,28 +143,30 @@ bool programHasConsole(const QString& filename);
QString toLocalPath(const QString& filename); QString toLocalPath(const QString& filename);
using LineProcessFunc = std::function<void(const QString&)>; using LineProcessFunc = std::function<void(const QString&)>;
QStringList ReadStreamToLines(QTextStream* stream); QStringList readStreamToLines(QTextStream* stream);
void ReadStreamToLines(QTextStream* stream, LineProcessFunc lineFunc); void readStreamToLines(QTextStream* stream, LineProcessFunc lineFunc);
QStringList TextToLines(const QString& text); QStringList textToLines(const QString& text);
void TextToLines(const QString& text, LineProcessFunc lineFunc); void textToLines(const QString& text, LineProcessFunc lineFunc);
QString LinesToText(const QStringList& lines); QString linesToText(const QStringList& lines);
QList<QByteArray> splitByteArrayToLines(const QByteArray& content);
QString parseMacros(const QString& s); QString parseMacros(const QString& s);
QStringList ReadFileToLines(const QString& fileName, QTextCodec* codec); QStringList readFileToLines(const QString& fileName, QTextCodec* codec);
QStringList ReadFileToLines(const QString& fileName); QStringList readFileToLines(const QString& fileName);
QByteArray ReadFileToByteArray(const QString& fileName); QByteArray readFileToByteArray(const QString& fileName);
void ReadFileToLines(const QString& fileName, QTextCodec* codec, LineProcessFunc lineFunc); void readFileToLines(const QString& fileName, QTextCodec* codec, LineProcessFunc lineFunc);
void StringsToFile(const QStringList& list, const QString& fileName); void stringsToFile(const QStringList& list, const QString& fileName);
void StringToFile(const QString& str, const QString& fileName); void stringToFile(const QString& str, const QString& fileName);
void decodeKey(int combinedKey, int& key, Qt::KeyboardModifiers& modifiers); void decodeKey(int combinedKey, int& key, Qt::KeyboardModifiers& modifiers);
void inflateRect(QRect& rect, int delta); void inflateRect(QRect& rect, int delta);
void inflateRect(QRect& rect, int dx, int dy); void inflateRect(QRect& rect, int dx, int dy);
QString TrimRight(const QString& s); QString trimRight(const QString& s);
QString TrimLeft(const QString& s); QString trimLeft(const QString& s);
bool StringIsBlank(const QString& s); bool stringIsBlank(const QString& s);
int compareFileModifiedTime(const QString& filename1, const QString& filename2); int compareFileModifiedTime(const QString& filename1, const QString& filename2);
QByteArray getHTTPBody(const QByteArray& content); QByteArray getHTTPBody(const QByteArray& content);
bool haveGoodContrast(const QColor& c1, const QColor &c2); bool haveGoodContrast(const QColor& c1, const QColor &c2);

View File

@ -147,7 +147,7 @@ void QConsole::addLine(const QString &line)
void QConsole::addText(const QString &text) void QConsole::addText(const QString &text)
{ {
QStringList lst = TextToLines(text); QStringList lst = textToLines(text);
for (const QString& line:lst) { for (const QString& line:lst) {
addLine(line); addLine(line);
} }