work save

This commit is contained in:
royqh1979@gmail.com 2021-08-27 16:38:55 +08:00
parent 61d1430a58
commit a5239aea48
12 changed files with 210 additions and 62 deletions

View File

@ -4,6 +4,9 @@ greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
CONFIG += c++17
QMAKE_CXXFLAGS_RELEASE += -Werror=return-type
QMAKE_CXXFLAGS_DEBUG += -Werror=return-type
# You can make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0

View File

@ -72,6 +72,7 @@ Editor::Editor(QWidget *parent, const QString& filename,
mParentPageControl->addTab(this,QString());
updateCaption();
}
PSynHighlighter highlighter;
if (!isNew) {
loadFile();
@ -96,7 +97,6 @@ Editor::Editor(QWidget *parent, const QString& filename,
} else {
initParser();
}
mCompletionPopup = std::make_shared<CodeCompletionView>();
applySettings();

View File

@ -43,12 +43,15 @@ MainWindow::MainWindow(QWidget *parent)
mFileInfoStatus=new QLabel();
mFileEncodingStatus = new QLabel();
mFileModeStatus = new QLabel();
mParsingInfoStatus = new QLabel();
mFileInfoStatus->setStyleSheet("margin-left:10px; margin-right:10px");
mFileEncodingStatus->setStyleSheet("margin-left:10px; margin-right:10px");
mFileModeStatus->setStyleSheet("margin-left:10px; margin-right:10px");
mParsingInfoStatus->setStyleSheet("margin-left:10px; margin-right:10px");
ui->statusbar->addWidget(mFileInfoStatus);
ui->statusbar->addWidget(mFileEncodingStatus);
ui->statusbar->addWidget(mFileModeStatus);
ui->statusbar->addWidget(mParsingInfoStatus);
mEditorList = new EditorList(ui->EditorTabsLeft,
ui->EditorTabsRight,
ui->splitterEditorPanel,
@ -458,6 +461,11 @@ void MainWindow::updateForStatusbarModeInfo()
}
}
void MainWindow::updateStatusBarForParsing(const QString &s)
{
mParsingInfoStatus->setText(s);
}
void MainWindow::openFiles(const QStringList &files)
{
mEditorList->beginUpdate();
@ -1570,6 +1578,50 @@ void MainWindow::onDebugEvaluateInput()
}
}
void MainWindow::onParserProgress(const QString &fileName, int total, int current)
{
// Mention every 5% progress
int showStep = total / 20;
// For Total = 1, avoid division by zero
if (showStep == 0)
showStep = 1;
// Only show if needed (it's a very slow operation)
if (current ==1 || current % showStep==0) {
updateStatusBarForParsing(tr("Parsing file %1 of %2: \"%3\"")
.arg(current).arg(total).arg(fileName));
}
}
void MainWindow::onStartParsing()
{
mParserTimer.restart();
}
void MainWindow::onEndParsing(int total, int)
{
double parseTime = mParserTimer.elapsed() / 1000;
double parsingFrequency;
if (total > 1) {
if (parseTime>0) {
parsingFrequency = total / parseTime;
} else {
parsingFrequency = 999;
}
updateStatusBarForParsing(tr("Done parsing %1 files in %2 seconds")
.arg(total).arg(parseTime)
+ " "
+ tr("(%1 files per second)")
.arg(parsingFrequency));
} else {
updateStatusBarForParsing(tr("Done parsing %1 files in %2 seconds")
.arg(total).arg(parseTime));
}
}
void MainWindow::on_actionFind_triggered()
{
Editor *e = mEditorList->getEditor();

View File

@ -50,6 +50,7 @@ public:
void updateForEncodingInfo();
void updateStatusbarForLineCol();
void updateForStatusbarModeInfo();
void updateStatusBarForParsing(const QString& s);
void updateEditorSettings();
void updateEditorActions();
void updateCompileActions();
@ -204,6 +205,9 @@ public slots:
void cleanUpCPUDialog();
void onDebugCommandInput(const QString& command);
void onDebugEvaluateInput();
void onParserProgress(const QString& fileName, int total, int current);
void onStartParsing();
void onEndParsing(int total, int updateView);
private:
void setupActions();
@ -216,6 +220,7 @@ private:
QLabel *mFileInfoStatus;
QLabel *mFileEncodingStatus;
QLabel *mFileModeStatus;
QLabel *mParsingInfoStatus;
QMenu *mMenuEncoding;
QMenu *mMenuEncodingList;
QMenu *mMenuRecentFiles;
@ -226,6 +231,7 @@ private:
SearchDialog *mSearchDialog;
QList<QAction *> mRecentFileActions;
bool mQuitting;
QElapsedTimer mParserTimer;
SearchResultModel mSearchResultModel;
PSearchResultListModel mSearchResultListModel;

View File

@ -26,6 +26,10 @@ CppParser::CppParser(QObject *parent) : QObject(parent)
mParseLocalHeaders = true;
mParseGlobalHeaders = true;
mLockCount = 0;
mIsSystemHeader = false;
mIsHeader = false;
mIsProjectFile = false;
//mNamespaces;
//mBlockBeginSkips;
//mBlockEndSkips;
@ -637,7 +641,7 @@ void CppParser::parseFile(const QString &fileName, bool inProject, bool onlyIfNo
for (QString file:files) {
if (isHfile(file)) {
mFilesScannedCount++;
emit onProgress(mCurrentFile,mFilesToScanCount,mFilesScannedCount);
emit onProgress(file,mFilesToScanCount,mFilesScannedCount);
if (!mPreprocessor.scannedFiles().contains(file)) {
internalParse(file);
}
@ -647,7 +651,7 @@ void CppParser::parseFile(const QString &fileName, bool inProject, bool onlyIfNo
for (QString file:files) {
if (isCfile(file)) {
mFilesScannedCount++;
emit onProgress(mCurrentFile,mFilesToScanCount,mFilesScannedCount);
emit onProgress(file,mFilesToScanCount,mFilesScannedCount);
if (!mPreprocessor.scannedFiles().contains(file)) {
internalParse(file);
}
@ -710,10 +714,13 @@ void CppParser::parseHardDefines()
QMutexLocker locker(&mMutex);
if (mParsing)
return;
int oldIsSystemHeader = mIsSystemHeader;
mIsSystemHeader = true;
mParsing=true;
{
auto action = finally([this]{
auto action = finally([&,this]{
mParsing = false;
mIsSystemHeader=oldIsSystemHeader;
});
for (PDefine define:mPreprocessor.hardDefines()) {
QString hintText = "#define";
@ -773,6 +780,9 @@ void CppParser::reset()
mInlineNamespaceEndSkips.clear();
mParseLocalHeaders = true;
mParseGlobalHeaders = true;
mIsSystemHeader = false;
mIsHeader = false;
mIsProjectFile = false;
mCurrentScope.clear();
mCurrentClassScope.clear();
@ -2242,7 +2252,7 @@ void CppParser::handlePreprocessor()
if (line == 1) {
mFilesScannedCount++;
mFilesToScanCount++;
onProgress(mCurrentFile,mFilesToScanCount,mFilesScannedCount);
emit onProgress(mCurrentFile,mFilesToScanCount,mFilesScannedCount);
}
}
} else if (mTokenizer[mIndex]->text.startsWith("#define ")) {
@ -2919,19 +2929,15 @@ void CppParser::internalParse(const QString &fileName)
// mPreprocessor.setIncludePaths(mIncludePaths);
// mPreprocessor.setProjectIncludePaths(mProjectIncludePaths);
mPreprocessor.setScanOptions(mParseGlobalHeaders, mParseLocalHeaders);
logToFile("preprocess + 1:","f:\\log.txt");
mPreprocessor.preprocess(fileName, buffer);
StringsToFile(mPreprocessor.result(),"f:\\preprocess.txt");
// with TStringList.Create do try
// Text:=fPreprocessor.Result;
// SaveToFile('f:\\Preprocess.txt');
// finally
// Free;
// end;
//fPreprocessor.DumpIncludesListTo('f:\\includes.txt');
// Tokenize the preprocessed buffer file
mTokenizer.tokenize(mPreprocessor.result());
if (mTokenizer.tokenCount() == 0)
return;
mTokenizer.dumpTokens("f:\\tokens.txt");
// Process the token list
mCurrentScope.clear();
@ -2946,14 +2952,10 @@ void CppParser::internalParse(const QString &fileName)
if (!handleStatement())
break;
}
#ifdef QT_DEBUG
// StringsToFile(mPreprocessor.result(),"f:\\preprocess.txt");
// mTokenizer.dumpTokens("f:\\tokens.txt");
// mPreprocessor.dumpDefinesTo("f:\\defines.txt");
// mPreprocessor.dumpIncludesListTo("f:\\includes.txt");
// mStatementList.dump("f:\\stats.txt");
mStatementList.dump("f:\\stats.txt");
// mStatementList.dumpAll("f:\\all-stats.txt");
#endif
}
}
@ -3118,6 +3120,8 @@ PStatement CppParser::doFindStatementInScope(const QString &name, const QString
void CppParser::internalInvalidateFile(const QString &fileName)
{
logToFile(QString("invalidate %1 start:").arg(fileName),"f:\\log.txt");
if (fileName.isEmpty())
return;
@ -3136,8 +3140,10 @@ void CppParser::internalInvalidateFile(const QString &fileName)
mNamespaces.remove(key);
}
}
logToFile(QString("invalidate %1 1:").arg(fileName),"f:\\log.txt");
// delete it from scannedfiles
mPreprocessor.scannedFiles().remove(fileName);
logToFile(QString("invalidate %1 2:").arg(fileName),"f:\\log.txt");
// remove its include files list
PFileIncludes p = findFileIncludes(fileName, true);
@ -3154,10 +3160,12 @@ void CppParser::internalInvalidateFile(const QString &fileName)
statement->hasDefinition = false;
}
}
logToFile(QString("invalidate %1 3:").arg(fileName),"f:\\log.txt");
for (PStatement statement:p->declaredStatements) {
mStatementList.deleteStatement(statement);
}
logToFile(QString("invalidate %1 4:").arg(fileName),"f:\\log.txt");
//p->declaredStatements.clear();
//p->statements.clear();
@ -3165,6 +3173,10 @@ void CppParser::internalInvalidateFile(const QString &fileName)
//p->dependedFiles.clear();
//p->dependingFiles.clear();
}
logToFile(QString("invalidate %1 10:").arg(fileName),"f:\\log.txt");
logToFile(QString("invalidate %1 end:").arg(fileName),"f:\\log.txt");
}
void CppParser::internalInvalidateFiles(const QSet<QString> &files)

View File

@ -3,6 +3,7 @@
#include <QFile>
#include <QTextCodec>
#include <QDebug>
CppPreprocessor::CppPreprocessor()
{
@ -169,9 +170,10 @@ void CppPreprocessor::dumpDefinesTo(const QString &fileName) const
if (file.open(QIODevice::WriteOnly|QIODevice::Truncate)) {
QTextStream stream(&file);
for (PDefine define:mDefines) {
stream<<QString("%1 %2 %3 %4\n").arg(define->name)
stream<<QString("%1 %2 %3 %4 %5\n").arg(define->name)
.arg(define->args).arg(define->value)
.arg(define->hardCoded)<<Qt::endl;
.arg(define->hardCoded).arg(define->formatValue)
<<Qt::endl;
}
}
}
@ -213,7 +215,7 @@ void CppPreprocessor::dumpIncludesListTo(const QString &fileName) const
QString CppPreprocessor::getNextPreprocessor()
{
logToFile("next preprocessor:","f:\\log.txt");
skipToPreprocessor(); // skip until # at start of line
int preProcFrom = mIndex;
if (preProcFrom >= mBuffer.count())
@ -481,7 +483,7 @@ QString CppPreprocessor::removeGCCAttributes(const QString &line)
QString newLine = "";
QString word = "";
int lenLine = line.length();
int i=1;
int i=0;
while(i< lenLine) {
if (isWordChar(line[i])) {
word += line[i];
@ -503,29 +505,28 @@ QString CppPreprocessor::removeGCCAttributes(const QString &line)
void CppPreprocessor::removeGCCAttribute(const QString &line, QString &newLine, int &i, const QString &word)
{
//no need it now
// int lenLine = line.length();
// int level = 0;
// if (word=="__attribute__") {
// while ( (i<lenLine) && isSpaceChar(line[i]))
// i++;
// if ((i<lenLine) && (line[i]=='(')) {
// level=0;
// while (i<lenLine) {
// switch(line[i].unicode()) {
// case '(': level++;
// break;
// case ')': level--;
// break;
// }
// i++;
// if (level==0)
// break;
// }
// }
// } else {
// newLine += word;
// }
int lenLine = line.length();
int level = 0;
if (word=="__attribute__") {
while ( (i<lenLine) && isSpaceChar(line[i]))
i++;
if ((i<lenLine) && (line[i]=='(')) {
level=0;
while (i<lenLine) {
switch(line[i].unicode()) {
case '(': level++;
break;
case ')': level--;
break;
}
i++;
if (level==0)
break;
}
}
} else {
newLine += word;
}
}
PParsedFile CppPreprocessor::getInclude(int index)
@ -733,6 +734,7 @@ void CppPreprocessor::parseArgs(PDefine define)
define->argList = args.split(',');
for (int i=0;i<define->argList.size();i++) {
define->argList[i]=define->argList[i].trimmed();
define->argUsed.append(false);
}
QStringList tokens = tokenizeValue(define->value);
@ -744,6 +746,7 @@ void CppPreprocessor::parseArgs(PDefine define)
}
int index = define->argList.indexOf(token);
if (index>=0) {
define->argUsed[index] = true;
if (lastToken == "#") {
formatStr+= "\"%"+QString("%1").arg(index+1)+"\"";
} else {
@ -751,6 +754,8 @@ void CppPreprocessor::parseArgs(PDefine define)
}
} else if (token == "%"){
formatStr+="%%";
} else if (token!="##" && token!="#"){
formatStr+=token;
}
lastToken = token;
}
@ -935,12 +940,17 @@ void CppPreprocessor::skipToEndOfPreprocessor()
void CppPreprocessor::skipToPreprocessor()
{
logToFile("skip:","f:\\log.txt");
// Increment until a line begins with a #
while ((mIndex < mBuffer.count()) && !mBuffer[mIndex].startsWith('#')) {
if (getCurrentBranch()) // if not skipping, expand current macros
mResult.append(expandMacros(mBuffer[mIndex],1));
else // If skipping due to a failed branch, clear line
mResult.append("");
logToFile(QString("tt %1 tt").arg(mIndex),"f:\\log.txt");
logToFile(QString("tt %1 tt").arg(mBuffer[mIndex]),"f:\\log.txt");
// if (getCurrentBranch()) // if not skipping, expand current macros
// mResult.append(expandMacros(mBuffer[mIndex],1));
// else // If skipping due to a failed branch, clear line
// mResult.append("");
mResult.append(mBuffer[mIndex]);
mIndex++;
}
}
@ -1048,6 +1058,7 @@ QString CppPreprocessor::expandDefines(QString line)
// Get identifier name (numbers are allowed, but not at the start
while ((tail < line.length()) && (isMacroIdentChar(line[tail]) || isDigit(line[head])))
tail++;
// qDebug()<<"1 "<<head<<tail<<line;
QString name = line.mid(head,tail-head);
int nameStart = head;
int nameEnd = tail;
@ -1077,6 +1088,7 @@ QString CppPreprocessor::expandDefines(QString line)
while ((tail < line.length()) && (isMacroIdentChar(line[tail]) || isDigit(line[tail])))
tail++;
}
// qDebug()<<"2 "<<defineStart<<tail<<line;
name = line.mid(defineStart, tail - defineStart);
PDefine define = getDefine(name);
QString insertValue;
@ -1104,6 +1116,7 @@ QString CppPreprocessor::expandDefines(QString line)
if ((tail < line.length()) && (line[tail] == '(')) {
head=tail;
if (skipBraces(line, tail)) {
// qDebug()<<"3 "<<line<<head<<tail;
QString args = line.mid(head,tail-head+1);
insertValue = expandFunction(define,args);
nameEnd = tail+1;
@ -1158,8 +1171,14 @@ QString CppPreprocessor::expandFunction(PDefine define, QString args)
}
QStringList argValues = args.split(",");
for (QString argValue:argValues) {
result=result.arg(argValue.trimmed());
if (argValues.length() == define->argList.length()
&& argValues.length()>0) {
for (int i=0;i<argValues.length();i++) {
if (define->argUsed[i]) {
QString argValue = argValues[i];
result=result.arg(argValue.trimmed());
}
}
}
result.replace("%%","%");

View File

@ -23,6 +23,7 @@ struct Define {
QString filename;
bool hardCoded;// if true, don't free memory (points to hard defines)
QStringList argList; // args list to format values
QList<bool> argUsed;
QString formatValue; // format template to format values
};

View File

@ -114,7 +114,8 @@ int StatementModel::deleteMember(StatementMap &map, PStatement statement)
{
if (!statement)
return 0;
map.remove(statement->command,statement);
//return map.remove(statement->command,statement);
return map.remove(statement->command,statement);
}
void StatementModel::dumpStatementMap(StatementMap &map, QTextStream &out, int level)

View File

@ -811,7 +811,7 @@ void Settings::Editor::doLoad()
mKeepCaretX = boolValue("keep_caret_x",true);
mCaretForInsert = static_cast<SynEditCaretType>( intValue("caret_for_insert",static_cast<int>(SynEditCaretType::ctVerticalLine)));
mCaretForOverwrite = static_cast<SynEditCaretType>( intValue("caret_for_overwrite",static_cast<int>(SynEditCaretType::ctBlock)));
mCaretColor = colorValue("caret_color",QColorConstants::Svg::black);
mCaretColor = colorValue("caret_color",QColorConstants::Svg::yellow);
//scroll
mAutoHideScrollbar = boolValue("auto_hide_scroll_bar", false);

View File

@ -17,6 +17,7 @@
#include <QDateTime>
#include "parser/cppparser.h"
#include "settings.h"
#include "mainwindow.h"
const QByteArray GuessTextEncoding(const QByteArray& text){
bool allAscii;
@ -540,6 +541,30 @@ void resetCppParser(std::shared_ptr<CppParser> parser)
parser->addHardDefineByLine("#define __TIME__ 1");
}
parser->parseHardDefines();
pMainWindow->disconnect(parser.get(),
&CppParser::onStartParsing,
pMainWindow,
&MainWindow::onStartParsing);
pMainWindow->disconnect(parser.get(),
&CppParser::onProgress,
pMainWindow,
&MainWindow::onParserProgress);
pMainWindow->disconnect(parser.get(),
&CppParser::onEndParsing,
pMainWindow,
&MainWindow::onEndParsing);
pMainWindow->connect(parser.get(),
&CppParser::onStartParsing,
pMainWindow,
&MainWindow::onStartParsing);
pMainWindow->connect(parser.get(),
&CppParser::onProgress,
pMainWindow,
&MainWindow::onParserProgress);
pMainWindow->connect(parser.get(),
&CppParser::onEndParsing,
pMainWindow,
&MainWindow::onEndParsing);
}
bool findComplement(const QString &s, const QChar &fromToken, const QChar &toToken, int &curPos, int increment)
@ -560,3 +585,18 @@ bool findComplement(const QString &s, const QChar &fromToken, const QChar &toTok
curPos = curPosBackup;
return false;
}
void logToFile(const QString &s, const QString &filename, bool append)
{
QFile file(filename);
QFile::OpenMode mode = QFile::WriteOnly;
if (append) {
mode |= QFile::Append;
} else {
mode |= QFile::Truncate;
}
if (file.open(mode)) {
QTextStream ts(&file);
ts<<s<<Qt::endl;
}
}

View File

@ -110,6 +110,7 @@ bool findComplement(const QString& s,
const QChar& toToken,
int& curPos,
int increment);
void logToFile(const QString& s, const QString& filename, bool append=true);
class CppParser;
void resetCppParser(std::shared_ptr<CppParser> parser);

View File

@ -3,6 +3,7 @@
#include <QKeyEvent>
#include <QVBoxLayout>
#include <QDebug>
CodeCompletionView::CodeCompletionView(QWidget *parent) :
QWidget(parent)
@ -17,6 +18,8 @@ CodeCompletionView::CodeCompletionView(QWidget *parent) :
mShowKeywords=true;
mUseCppKeyword=true;
mRecordUsage = false;
mSortByScope = true;
mOnlyGlobals = false;
mShowCount = 1000;
@ -210,16 +213,16 @@ static bool sortByScopeComparator(PStatement statement1,PStatement statement2){
} else if (statement2->kind == StatementKind::skKeyword) {
return false;
// Show stuff from local headers first
} else if (statement1->inSystemHeader && ! statement2->inSystemHeader) {
} else if (statement1->inSystemHeader && (!statement2->inSystemHeader)) {
return true;
} else if (!statement1->inSystemHeader && statement2->inSystemHeader) {
} else if ((!statement1->inSystemHeader) && statement2->inSystemHeader) {
return false;
// Show local statements first
} else if (statement1->scope != StatementScope::ssGlobal
&& statement1->scope == StatementScope::ssGlobal ) {
&& statement2->scope == StatementScope::ssGlobal ) {
return true;
} else if (statement1->scope == StatementScope::ssGlobal
&& statement1->scope != StatementScope::ssGlobal ) {
&& statement2->scope != StatementScope::ssGlobal ) {
return false;
// otherwise, sort by name
} else
@ -280,17 +283,16 @@ static bool sortByScopeWithUsageComparator(PStatement statement1,PStatement stat
return false;
// Show local statements first
} else if (statement1->scope != StatementScope::ssGlobal
&& statement1->scope == StatementScope::ssGlobal ) {
&& statement2->scope == StatementScope::ssGlobal ) {
return true;
} else if (statement1->scope == StatementScope::ssGlobal
&& statement1->scope != StatementScope::ssGlobal ) {
&& statement2->scope != StatementScope::ssGlobal ) {
return false;
// otherwise, sort by name
} else
return statement1->command < statement2->command;
}
void CodeCompletionView::filterList(const QString &member)
{
QMutexLocker locker(&mMutex);
@ -403,8 +405,10 @@ void CodeCompletionView::getCompletionFor(const QString &fileName, const QString
for (QString keyword:CppDirectives) {
PStatement statement = std::make_shared<Statement>();
statement->command = keyword;
statement->kind = StatementKind::skPreprocessor;
statement->kind = StatementKind::skKeyword;
statement->fullName = keyword;
statement->usageCount = 0;
statement->freqTop = 0;
mFullCompletionStatementList.append(statement);
}
}
@ -419,6 +423,8 @@ void CodeCompletionView::getCompletionFor(const QString &fileName, const QString
statement->command = keyword;
statement->kind = StatementKind::skKeyword;
statement->fullName = keyword;
statement->usageCount = 0;
statement->freqTop = 0;
mFullCompletionStatementList.append(statement);
}
}
@ -437,6 +443,8 @@ void CodeCompletionView::getCompletionFor(const QString &fileName, const QString
statement->command = codeIn->prefix;
statement->kind = StatementKind::skUserCodeIn;
statement->fullName = codeIn->prefix;
statement->usageCount = 0;
statement->freqTop = 0;
mFullCompletionStatementList.append(statement);
}
}
@ -449,6 +457,8 @@ void CodeCompletionView::getCompletionFor(const QString &fileName, const QString
statement->command = keyword;
statement->kind = StatementKind::skKeyword;
statement->fullName = keyword;
statement->usageCount = 0;
statement->freqTop = 0;
mFullCompletionStatementList.append(statement);
}
} else {
@ -457,6 +467,8 @@ void CodeCompletionView::getCompletionFor(const QString &fileName, const QString
statement->command = keyword;
statement->kind = StatementKind::skKeyword;
statement->fullName = keyword;
statement->usageCount = 0;
statement->freqTop = 0;
mFullCompletionStatementList.append(statement);
}
}
@ -805,10 +817,11 @@ void CodeCompletionView::hideEvent(QHideEvent *event)
bool CodeCompletionView::event(QEvent *event)
{
QWidget::event(event);
bool result = QWidget::event(event);
if (event->type() == QEvent::FontChange) {
mListView->setFont(font());
mListView->setFont(font());
}
return result;
}
CodeCompletionListView::CodeCompletionListView(QWidget *parent) : QListView(parent)