diff --git a/RedPandaIDE/HighlighterManager.cpp b/RedPandaIDE/HighlighterManager.cpp index 7ee79a71..e170122a 100644 --- a/RedPandaIDE/HighlighterManager.cpp +++ b/RedPandaIDE/HighlighterManager.cpp @@ -17,10 +17,10 @@ #include "HighlighterManager.h" #include #include -#include "qsynedit/highlighter/cpp.h" -#include "qsynedit/highlighter/asm.h" -#include "qsynedit/highlighter/glsl.h" -#include "qsynedit/Constants.h" +#include "highlighter/cpp.h" +#include "highlighter/asm.h" +#include "highlighter/glsl.h" +#include "Constants.h" #include "colorscheme.h" HighlighterManager highlighterManager; diff --git a/RedPandaIDE/HighlighterManager.h b/RedPandaIDE/HighlighterManager.h index 9f353130..a4b027bf 100644 --- a/RedPandaIDE/HighlighterManager.h +++ b/RedPandaIDE/HighlighterManager.h @@ -16,7 +16,7 @@ */ #ifndef HIGHLIGHTERMANAGER_H #define HIGHLIGHTERMANAGER_H -#include "qsynedit/highlighter/base.h" +#include "highlighter/base.h" class HighlighterManager { diff --git a/RedPandaIDE/RedPandaIDE.pro b/RedPandaIDE/RedPandaIDE.pro index 9ba720db..06ad8177 100644 --- a/RedPandaIDE/RedPandaIDE.pro +++ b/RedPandaIDE/RedPandaIDE.pro @@ -52,6 +52,8 @@ msvc { # 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 +INCLUDEPATH += ../libs/qsynedit ../libs/redpanda_qt_utils + SOURCES += \ HighlighterManager.cpp \ autolinkmanager.cpp \ @@ -65,7 +67,6 @@ SOURCES += \ compiler/runner.cpp \ customfileiconprovider.cpp \ gdbmiresultparser.cpp \ - platform.cpp \ compiler/compiler.cpp \ compiler/compilermanager.cpp \ compiler/executablerunner.cpp \ @@ -207,7 +208,6 @@ HEADERS += \ parser/cpptokenizer.h \ parser/parserutils.h \ parser/statementmodel.h \ - platform.h \ problems/ojproblemset.h \ problems/problemcasevalidator.h \ project.h \ diff --git a/RedPandaIDE/colorscheme.cpp b/RedPandaIDE/colorscheme.cpp index e5f7befb..39c447d5 100644 --- a/RedPandaIDE/colorscheme.cpp +++ b/RedPandaIDE/colorscheme.cpp @@ -22,7 +22,7 @@ #include #include "utils.h" #include "settings.h" -#include "qsynedit/Constants.h" +#include "Constants.h" ColorManager * pColorManager; diff --git a/RedPandaIDE/colorscheme.h b/RedPandaIDE/colorscheme.h index 1d50b85e..69d4d1a1 100644 --- a/RedPandaIDE/colorscheme.h +++ b/RedPandaIDE/colorscheme.h @@ -18,7 +18,7 @@ #define COLORSCHEME_H #include -#include "qsynedit/highlighter/base.h" +#include "highlighter/base.h" #include "parser/statementmodel.h" #define EXT_COLOR_SCHEME ".scheme" diff --git a/RedPandaIDE/compiler/compiler.cpp b/RedPandaIDE/compiler/compiler.cpp index 31f3315d..2cddb4e7 100644 --- a/RedPandaIDE/compiler/compiler.cpp +++ b/RedPandaIDE/compiler/compiler.cpp @@ -30,7 +30,7 @@ #include "../editorlist.h" #include "../parser/cppparser.h" #include "../autolinkmanager.h" -#include "../platform.h" +#include "charsetinfo.h" #include "../project.h" #define COMPILE_PROCESS_END "---//END//----" diff --git a/RedPandaIDE/compiler/compilermanager.cpp b/RedPandaIDE/compiler/compilermanager.cpp index ae3bea5b..72906135 100644 --- a/RedPandaIDE/compiler/compilermanager.cpp +++ b/RedPandaIDE/compiler/compilermanager.cpp @@ -25,7 +25,7 @@ #include #include #include "projectcompiler.h" -#include "../platform.h" +#include "charsetinfo.h" enum RunProgramFlag { RPF_PAUSE_CONSOLE = 0x0001, diff --git a/RedPandaIDE/compiler/projectcompiler.cpp b/RedPandaIDE/compiler/projectcompiler.cpp index a7c7445d..079be2c2 100644 --- a/RedPandaIDE/compiler/projectcompiler.cpp +++ b/RedPandaIDE/compiler/projectcompiler.cpp @@ -18,7 +18,7 @@ #include "../project.h" #include "compilermanager.h" #include "../systemconsts.h" -#include "../platform.h" +#include "charsetinfo.h" #include "../editor.h" #include diff --git a/RedPandaIDE/compiler/stdincompiler.cpp b/RedPandaIDE/compiler/stdincompiler.cpp index ad83111a..23a1cc46 100644 --- a/RedPandaIDE/compiler/stdincompiler.cpp +++ b/RedPandaIDE/compiler/stdincompiler.cpp @@ -19,7 +19,7 @@ #include #include #include -#include "../platform.h" +#include "charsetinfo.h" StdinCompiler::StdinCompiler(const QString &filename,const QByteArray& encoding, const QString& content,bool silent, bool onlyCheckSyntax): Compiler(filename,silent, onlyCheckSyntax), diff --git a/RedPandaIDE/editor.h b/RedPandaIDE/editor.h index 6747a631..9c5e3290 100644 --- a/RedPandaIDE/editor.h +++ b/RedPandaIDE/editor.h @@ -20,7 +20,7 @@ #include #include #include -#include "qsynedit/SynEdit.h" +#include "SynEdit.h" #include "colorscheme.h" #include "common.h" #include "parser/cppparser.h" diff --git a/RedPandaIDE/project.cpp b/RedPandaIDE/project.cpp index 56225a91..67b814b0 100644 --- a/RedPandaIDE/project.cpp +++ b/RedPandaIDE/project.cpp @@ -21,7 +21,7 @@ #include "editorlist.h" #include #include "utils.h" -#include "platform.h" +#include "charsetinfo.h" #include "projecttemplate.h" #include "systemconsts.h" #include "iconsmanager.h" diff --git a/RedPandaIDE/settings.h b/RedPandaIDE/settings.h index e5f4d6e1..35111e85 100644 --- a/RedPandaIDE/settings.h +++ b/RedPandaIDE/settings.h @@ -23,8 +23,9 @@ #include #include #include -#include "qsynedit/SynEdit.h" +#include "SynEdit.h" #include "compiler/compilerinfo.h" +#include "utils.h" /** * use the following command to get gcc's default bin/library folders: diff --git a/Red_Panda_CPP.pro b/Red_Panda_CPP.pro index ebad45f6..b5a23865 100644 --- a/Red_Panda_CPP.pro +++ b/Red_Panda_CPP.pro @@ -2,24 +2,33 @@ TEMPLATE = subdirs SUBDIRS += \ RedPandaIDE \ - tools/astyle \ - tools/consolepauser - libs/qsynedit + astyle \ + consolepauser \ + redpanda_qt_utils \ + qsynedit + +astyle.subdir = tools/astyle +consolepauser.subdir = tools/consolepauser +redpanda_qt_utils.subdir = libs/redpanda_qt_utils +qsynedit.subdir = libs/qsynedit # Add the dependencies so that the RedPandaIDE project can add the depended programs # into the main app bundle -RedPandaIDE.depends = tools/astyle tools/consolepauser libs/qsynedit +RedPandaIDE.depends = astyle consolepauser qsynedit +qsynedit.depends = redpanda_qt_utils win32: { SUBDIRS += \ - tools/redpanda-win-git-askpass - RedPandaIDE.depends += tools/redpanda-win-git-askpass + redpanda-win-git-askpass +redpanda-win-git-askpass.subdir = tools/redpanda-win-git-askpass +RedPandaIDE.depends += redpanda-win-git-askpass } unix: { SUBDIRS += \ - tools/redpanda-git-askpass - RedPandaIDE.depends += tools/redpanda-git-askpass + redpanda-git-askpass +redpanda-git-askpass.subdir = tools/redpanda-git-askpass +RedPandaIDE.depends += redpanda-git-askpass } APP_NAME = RedPandaCPP diff --git a/libs/qsynedit/KeyStrokes.h b/libs/qsynedit/KeyStrokes.h index 2bcf0de5..e73b0aee 100644 --- a/libs/qsynedit/KeyStrokes.h +++ b/libs/qsynedit/KeyStrokes.h @@ -21,6 +21,7 @@ #include #include #include "MiscClasses.h" +#include "redpanda_utils.h" namespace QSynedit { //**************************************************************************** diff --git a/libs/qsynedit/MiscClasses.cpp b/libs/qsynedit/MiscClasses.cpp index b4227a27..6c686478 100644 --- a/libs/qsynedit/MiscClasses.cpp +++ b/libs/qsynedit/MiscClasses.cpp @@ -336,26 +336,4 @@ void SynGutter::setBorderColor(const QColor &value) } } -BaseError::BaseError(const QString &reason): -mReason(reason) -{ - -} - -QString BaseError::reason() const -{ - return mReason; -} - -IndexOutOfRange::IndexOutOfRange(int Index): -BaseError(QObject::tr("Index %1 out of range").arg(Index)) -{ - -} - -FileError::FileError(const QString &reason): BaseError(reason) -{ -} - - } diff --git a/libs/qsynedit/MiscClasses.h b/libs/qsynedit/MiscClasses.h index df8b7f51..cbf3019c 100644 --- a/libs/qsynedit/MiscClasses.h +++ b/libs/qsynedit/MiscClasses.h @@ -24,25 +24,6 @@ namespace QSynedit { -class BaseError{ -public: - explicit BaseError(const QString& reason) ; - QString reason() const; - -protected: - QString mReason; -}; - -class IndexOutOfRange:public BaseError { -public: - explicit IndexOutOfRange(int Index); -}; - -class FileError: public BaseError { -public: - explicit FileError(const QString& reason); -}; - enum class SynGutterBorderStyle { None, Middle, diff --git a/libs/qsynedit/MiscProcs.cpp b/libs/qsynedit/MiscProcs.cpp index 180ac419..a0eb83e8 100644 --- a/libs/qsynedit/MiscProcs.cpp +++ b/libs/qsynedit/MiscProcs.cpp @@ -201,68 +201,4 @@ int calSpanLines(const BufferCoord &startPos, const BufferCoord &endPos) return std::abs(endPos.line - startPos.line+1); } -void decodeKey(const int combinedKey, int &key, Qt::KeyboardModifiers &modifiers) -{ - modifiers = Qt::NoModifier; - if (combinedKey & Qt::ShiftModifier) { - modifiers|=Qt::ShiftModifier; - } - if (combinedKey & Qt::ControlModifier) { - modifiers|=Qt::ControlModifier; - } - if (combinedKey & Qt::AltModifier) { - modifiers|=Qt::AltModifier; - } - if (combinedKey & Qt::MetaModifier) { - modifiers|=Qt::MetaModifier; - } - if (combinedKey & Qt::KeypadModifier) { - modifiers|= Qt::KeypadModifier; - } - key = combinedKey & ~(Qt::ShiftModifier | Qt::ControlModifier | Qt::AltModifier | Qt::MetaModifier | Qt::KeypadModifier); -} - -float pointToPixel(float point) -{ - return point * screenDPI() / 72; -} - -float pixelToPoint(float pixel) -{ - return pixel * 72 / screenDPI(); -} - -float pointToPixel(float point, float dpi) -{ - return point * dpi / 72; -} - -static int defaultScreenDPI = -1; - -int screenDPI() -{ - if (defaultScreenDPI<1) { - defaultScreenDPI = qApp->primaryScreen()->logicalDotsPerInch(); - } - return defaultScreenDPI; -} - -void setScreenDPI(int dpi) -{ - defaultScreenDPI = dpi; -} - -void inflateRect(QRect &rect, int delta) -{ - inflateRect(rect,delta,delta); -} - -void inflateRect(QRect &rect, int dx, int dy) -{ - rect.setLeft(rect.left()-dx); - rect.setRight(rect.right()+dx); - rect.setTop(rect.top()-dy); - rect.setBottom(rect.bottom()+dy); -} - } diff --git a/libs/qsynedit/MiscProcs.h b/libs/qsynedit/MiscProcs.h index ad4872ba..07578c2f 100644 --- a/libs/qsynedit/MiscProcs.h +++ b/libs/qsynedit/MiscProcs.h @@ -90,59 +90,5 @@ int findLastNonWordChar(const QString& s, int startPos); void ensureNotAfter(BufferCoord& cord1, BufferCoord& cord2); bool isWordChar(const QChar& ch); - -void decodeKey(int combinedKey, int& key, Qt::KeyboardModifiers& modifiers); - -int screenDPI(); -void setScreenDPI(int dpi); -float pointToPixel(float point); -float pointToPixel(float point, float dpi); -float pixelToPoint(float pixel); - -void inflateRect(QRect& rect, int delta); -void inflateRect(QRect& rect, int dx, int dy); - - - -/** - * from https://github.com/Microsoft/GSL - **/ - -template -class final_action -{ -public: - static_assert(!std::is_reference::value && !std::is_const::value && - !std::is_volatile::value, - "Final_action should store its callable by value"); - - explicit final_action(F f) noexcept : f_(std::move(f)) {} - - final_action(final_action&& other) noexcept - : f_(std::move(other.f_)), invoke_(std::exchange(other.invoke_, false)) - {} - - final_action(const final_action&) = delete; - final_action& operator=(const final_action&) = delete; - final_action& operator=(final_action&&) = delete; - - ~final_action() noexcept - { - if (invoke_) f_(); - } - -private: - F f_; - bool invoke_{true}; -}; - -template final_action::type>::type> -finally(F&& f) noexcept -{ - return final_action::type>::type>( - std::forward(f)); } - -} - #endif // MISCPROCS_H diff --git a/libs/qsynedit/TextBuffer.cpp b/libs/qsynedit/TextBuffer.cpp index 98770ca9..6b1c1156 100644 --- a/libs/qsynedit/TextBuffer.cpp +++ b/libs/qsynedit/TextBuffer.cpp @@ -15,6 +15,7 @@ * along with this program. If not, see . */ #include "TextBuffer.h" +#include "redpanda_utils.h" #include #include #include @@ -24,6 +25,8 @@ #include "SynEdit.h" #include #include +#include "charsetinfo.h" +#include namespace QSynedit { diff --git a/libs/qsynedit/TextBuffer.h b/libs/qsynedit/TextBuffer.h index d96a7a04..295ded3c 100644 --- a/libs/qsynedit/TextBuffer.h +++ b/libs/qsynedit/TextBuffer.h @@ -26,6 +26,7 @@ #include #include "MiscProcs.h" #include "Types.h" +#include "redpanda_utils.h" namespace QSynedit { enum SynEditStringFlag { diff --git a/libs/qsynedit/Types.h b/libs/qsynedit/Types.h index e95eaaa2..dace15fa 100644 --- a/libs/qsynedit/Types.h +++ b/libs/qsynedit/Types.h @@ -24,19 +24,6 @@ namespace QSynedit { - -#define ENCODING_AUTO_DETECT "AUTO" -#define ENCODING_UTF8 "UTF-8" -#define ENCODING_UTF8_BOM "UTF-8 BOM" -#define ENCODING_SYSTEM_DEFAULT "SYSTEM" -#define ENCODING_ASCII "ASCII" - -enum class FileEndingType { - Windows, - Linux, - Mac -};// Windows: CRLF, UNIX: LF, Mac: CR - enum class SynSelectionMode {Normal, Line, Column}; struct BufferCoord { diff --git a/libs/qsynedit/qsynedit.pro b/libs/qsynedit/qsynedit.pro index 14261a4e..ad7035fd 100644 --- a/libs/qsynedit/qsynedit.pro +++ b/libs/qsynedit/qsynedit.pro @@ -59,3 +59,6 @@ HEADERS += Search.h \ highlighter/composition.h \ highlighter/cpp.h \ highlighter/glsl.h \ + +INCLUDEPATH += ../redpanda_qt_utils +LIBS += -lredpand_qt_utils \ No newline at end of file diff --git a/libs/redpanda_qt_utils/charsetinfo.cpp b/libs/redpanda_qt_utils/charsetinfo.cpp index 10439f63..4c9d1d17 100644 --- a/libs/redpanda_qt_utils/charsetinfo.cpp +++ b/libs/redpanda_qt_utils/charsetinfo.cpp @@ -14,7 +14,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -#include "platform.h" +#include "charsetinfo.h" #include #include #include diff --git a/libs/redpanda_qt_utils/redpand_qt_utils.pro b/libs/redpanda_qt_utils/redpanda_qt_utils.pro similarity index 91% rename from libs/redpanda_qt_utils/redpand_qt_utils.pro rename to libs/redpanda_qt_utils/redpanda_qt_utils.pro index 2f1a6df1..59b52552 100644 --- a/libs/redpanda_qt_utils/redpand_qt_utils.pro +++ b/libs/redpanda_qt_utils/redpanda_qt_utils.pro @@ -5,6 +5,7 @@ greaterThan(QT_MAJOR_VERSION, 4): QT += widgets CONFIG += c++17 CONFIG += nokey +CONFIG += staticlib win32: { DEFINES += _WIN32_WINNT=0x0601 @@ -23,4 +24,4 @@ SOURCES += redpanda_utils.cpp \ charsetinfo.cpp HEADERS += redpanda_utils.h \ - charsetinfo.h \ No newline at end of file + charsetinfo.h diff --git a/libs/redpanda_qt_utils/redpanda_utils.cpp b/libs/redpanda_qt_utils/redpanda_utils.cpp index a2472f68..c9ae2ab6 100644 --- a/libs/redpanda_qt_utils/redpanda_utils.cpp +++ b/libs/redpanda_qt_utils/redpanda_utils.cpp @@ -14,8 +14,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -#include "utils.h" -#include "systemconsts.h" +#include "redpanda_utils.h" #include #include #include @@ -32,19 +31,13 @@ #include #include #include -#include "parser/cppparser.h" -#include "settings.h" -#include "mainwindow.h" -#include "editorlist.h" -#include "editor.h" -#include "project.h" -#include "compiler/executablerunner.h" #ifdef Q_OS_WIN +#include #include #include #endif -const QByteArray GuessTextEncoding(const QByteArray& text){ +const QByteArray guessTextEncoding(const QByteArray& text){ bool allAscii; int ii; int size; @@ -91,6 +84,8 @@ const QByteArray GuessTextEncoding(const QByteArray& text){ return ENCODING_UTF8; } + + bool isTextAllAscii(const QByteArray& text) { for (char c:text) { if (c<0) { @@ -109,259 +104,136 @@ bool isTextAllAscii(const QString& text) { return true; } -#ifdef Q_OS_WIN -static bool gIsGreenEdition = true; -static bool gIsGreenEditionInited = false; -#endif -bool isGreenEdition() -{ -#ifdef Q_OS_WIN - if (!gIsGreenEditionInited) { - QString keyString = QString("Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\RedPanda-C++"); - QString value; - if (!readRegistry(HKEY_LOCAL_MACHINE,keyString.toLocal8Bit(),"UninstallString",value)) { - keyString = "SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\RedPanda-C++"; - if (!readRegistry(HKEY_LOCAL_MACHINE,keyString.toLocal8Bit(),"UninstallString",value)) { - value=""; - } - } - if (!value.isEmpty()) { - QString regPath = extractFileDir(value); - - QString appPath = QApplication::instance()->applicationDirPath(); - gIsGreenEdition = excludeTrailingPathDelimiter(regPath).compare(excludeTrailingPathDelimiter(appPath), - Qt::CaseInsensitive)!=0; - } - gIsGreenEditionInited = true; - } - return gIsGreenEdition; -#else - return false; -#endif -} - -QByteArray runAndGetOutput(const QString &cmd, const QString& workingDir, const QStringList& arguments, - const QByteArray &inputContent, bool inheritEnvironment, - const QProcessEnvironment& env) -{ - QProcess process; - QByteArray result; - if (env.isEmpty()) { - if (inheritEnvironment) { - process.setProcessEnvironment(QProcessEnvironment::systemEnvironment()); - } else { - process.setProcessEnvironment(QProcessEnvironment()); - } - } else { - process.setProcessEnvironment(env); - } - process.setWorkingDirectory(workingDir); - process.connect(&process,&QProcess::readyReadStandardError, - [&](){ - result.append(process.readAllStandardError()); - }); - process.connect(&process,&QProcess::readyReadStandardOutput, - [&](){ - result.append(process.readAllStandardOutput()); - }); - process.start(cmd,arguments); - if (!inputContent.isEmpty()) { - process.write(inputContent); - } - process.closeWriteChannel(); - process.waitForFinished(); - return result; -} - bool isNonPrintableAsciiChar(char ch) { return (ch<=32) && (ch>=0); } -bool fileExists(const QString &file) -{ - if (file.isEmpty()) - return false; - return QFile(file).exists(); -} - -bool fileExists(const QString &dir, const QString &fileName) -{ - if (dir.isEmpty() || fileName.isEmpty()) - return false; - QDir dirInfo(dir); - return dirInfo.exists(fileName); -} - -bool directoryExists(const QString &file) -{ - if (file.isEmpty()) - return false; - QFileInfo dir(file); - return dir.exists() && dir.isDir(); -} - -QString includeTrailingPathDelimiter(const QString &path) -{ - if (path.endsWith('/') || path.endsWith(QDir::separator())) { - return path; - } else { - return path + "/"; - } -} - -QString excludeTrailingPathDelimiter(const QString &path) -{ - int pos = path.length()-1; - while (pos>=0 && (path[pos]=='/' || path[pos]==QDir::separator())) - pos--; - return path.mid(0,pos+1); -} - -FileType getFileType(const QString &filename) -{ - if (filename.endsWith(".dev",PATH_SENSITIVITY)) { - return FileType::Project; - } - if (filename.endsWith(".C")) { - return FileType::CppSource; - } - if (filename.endsWith(".CPP")) { - return FileType::CppSource; - } - if (filename.endsWith(".c",PATH_SENSITIVITY)) { - return FileType::CSource; - } - if (filename.endsWith(".cpp",PATH_SENSITIVITY)) { - return FileType::CppSource; - } - if (filename.endsWith(".cc",PATH_SENSITIVITY)) { - return FileType::CppSource; - } - if (filename.endsWith(".cxx",PATH_SENSITIVITY)) { - return FileType::CppSource; - } - if (filename.endsWith(".c++",PATH_SENSITIVITY)) { - return FileType::CppSource; - } - if (filename.endsWith(".H")) { - return FileType::CHeader; - } - if (filename.endsWith(".h",PATH_SENSITIVITY)) { - return FileType::CHeader; - } - if (filename.endsWith(".hpp",PATH_SENSITIVITY)) { - return FileType::CppHeader; - } - if (filename.endsWith(".hh",PATH_SENSITIVITY)) { - return FileType::CppHeader; - } - if (filename.endsWith(".hxx",PATH_SENSITIVITY)) { - return FileType::CppHeader; - } - if (filename.endsWith(".inl",PATH_SENSITIVITY)) { - return FileType::CppHeader; - } - if (filename.endsWith(".rc",PATH_SENSITIVITY)) { - return FileType::WindowsResourceSource; - } - if (filename.endsWith(".in",PATH_SENSITIVITY)) { - return FileType::Text; - } - if (filename.endsWith(".out",PATH_SENSITIVITY)) { - return FileType::Text; - } - if (filename.endsWith(".txt",PATH_SENSITIVITY)) { - return FileType::Text; - } - if (filename.endsWith(".dat",PATH_SENSITIVITY)) { - return FileType::Text; - } - QMimeDatabase db; - QMimeType mimeType=db.mimeTypeForFile(filename); - if (mimeType.isValid() && mimeType.name().startsWith("text/")) { - return FileType::Text; - } - return FileType::Other; -} - - -QString getCompiledExecutableName(const QString& filename) -{ - return changeFileExt(filename,EXECUTABLE_EXT); -} - -void splitStringArguments(const QString &arguments, QStringList &argumentList) -{ - QString word; - bool inQuota; - inQuota = false; - for (QChar ch:arguments) { - if (ch == '"') { - inQuota = !inQuota; - } else if (ch == '\n' || ch == ' ' || ch == '\t' || ch == '\r') { - if (!inQuota) { - word = word.trimmed(); - if (!word.isEmpty()) { - argumentList.append(word); - } - word = ""; - } else { - word.append(ch); - } - } else { - word.append(ch); - } - } - word = word.trimmed(); - if (!word.isEmpty()) { - argumentList.append(word); - } -} - -bool programHasConsole(const QString & filename) -{ -#ifdef Q_OS_WIN - bool result = false; - HANDLE handle = CreateFile(filename.toStdWString().c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); - if (handle != INVALID_HANDLE_VALUE) { - IMAGE_DOS_HEADER dos_header; - DWORD signature; - DWORD bytesread; - IMAGE_FILE_HEADER pe_header; - IMAGE_OPTIONAL_HEADER opt_header; - - ReadFile(handle, &dos_header, sizeof(dos_header), &bytesread, NULL); - SetFilePointer(handle, dos_header.e_lfanew, NULL, 0); - ReadFile(handle, &signature, sizeof(signature), &bytesread, NULL); - ReadFile(handle, &pe_header, sizeof(pe_header), &bytesread, NULL); - ReadFile(handle, &opt_header, sizeof(opt_header), &bytesread, NULL); - - result = (opt_header.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI); - } - CloseHandle(handle); - return result; -#else - return true; -#endif -} - QStringList textToLines(const QString &text) { QTextStream stream(&((QString&)text),QIODevice::ReadOnly); return readStreamToLines(&stream); } -QStringList readFileToLines(const QString& fileName, QTextCodec* codec) + +void textToLines(const QString &text, LineProcessFunc lineFunc) { - QFile file(fileName); - if (file.open(QFile::ReadOnly)) { - QTextStream stream(&file); - stream.setCodec(codec); - stream.setAutoDetectUnicode(false); - return readStreamToLines(&stream); + QTextStream stream(&((QString&)text),QIODevice::ReadOnly); + readStreamToLines(&stream,lineFunc); +} + +QString linesToText(const QStringList &lines, const QString& lineBreak) +{ + return lines.join(lineBreak); +} + +QList splitByteArrayToLines(const QByteArray &content) +{ + QList 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++; + } } - return QStringList(); + if (lineStart>end) { + lines.append(""); + } else { + line = QByteArray(lineStart, end-lineStart+1); + lines.append(line); + } + return lines; +} + +QString trimRight(const QString &s) +{ + if (s.isEmpty()) + return s; + int i = s.length()-1; +// while ((i>=0) && ((s[i] == '\r') || (s[i]=='\n') || (s[i] == '\t') || (s[i]==' '))) { + while ((i>=0) && (s[i]<=32)) { + i--; + }; + if (i>=0) { + return s.left(i+1); + } else { + return QString(); + } +} + +QString trimLeft(const QString &s) +{ + if (s.isEmpty()) + return s; + int i=0; +// while ((i32) + break; + n++; + } + return n; +} + +bool stringIsBlank(const QString &s) +{ + for (QChar ch:s) { + if (ch != ' ' && ch != '\t') + return false; + } + return true; +} + +QByteArray toByteArray(const QString &s) +{ + //return s.toLocal8Bit(); + return s.toUtf8(); +} + +QString fromByteArray(const QByteArray &s) +{ + QTextCodec* codec = QTextCodec::codecForName(ENCODING_UTF8); + QTextCodec::ConverterState state; + if (!codec) + return QString(s); + QString tmp = codec->toUnicode(s,s.length(),&state); + if (state.invalidChars>0) + tmp = QString::fromLocal8Bit(s); + return tmp; } QStringList readStreamToLines(QTextStream *stream) @@ -383,10 +255,16 @@ void readStreamToLines(QTextStream *stream, } } -void textToLines(const QString &text, LineProcessFunc lineFunc) +QStringList readFileToLines(const QString& fileName, QTextCodec* codec) { - QTextStream stream(&((QString&)text),QIODevice::ReadOnly); - readStreamToLines(&stream,lineFunc); + QFile file(fileName); + if (file.open(QFile::ReadOnly)) { + QTextStream stream(&file); + stream.setCodec(codec); + stream.setAutoDetectUnicode(false); + return readStreamToLines(&stream); + } + return QStringList(); } void readFileToLines(const QString &fileName, QTextCodec *codec, LineProcessFunc lineFunc) @@ -400,164 +278,6 @@ void readFileToLines(const QString &fileName, QTextCodec *codec, LineProcessFunc } } -BaseError::BaseError(const QString &reason): -mReason(reason) -{ - -} - -QString BaseError::reason() const -{ - return mReason; -} - -IndexOutOfRange::IndexOutOfRange(int Index): -BaseError(QObject::tr("Index %1 out of range").arg(Index)) -{ - -} - -FileError::FileError(const QString &reason): BaseError(reason) -{ - -} - -void decodeKey(const int combinedKey, int &key, Qt::KeyboardModifiers &modifiers) -{ - modifiers = Qt::NoModifier; - if (combinedKey & Qt::ShiftModifier) { - modifiers|=Qt::ShiftModifier; - } - if (combinedKey & Qt::ControlModifier) { - modifiers|=Qt::ControlModifier; - } - if (combinedKey & Qt::AltModifier) { - modifiers|=Qt::AltModifier; - } - if (combinedKey & Qt::MetaModifier) { - modifiers|=Qt::MetaModifier; - } - if (combinedKey & Qt::KeypadModifier) { - modifiers|= Qt::KeypadModifier; - } - key = combinedKey & ~(Qt::ShiftModifier | Qt::ControlModifier | Qt::AltModifier | Qt::MetaModifier | Qt::KeypadModifier); -} - -void inflateRect(QRect &rect, int delta) -{ - inflateRect(rect,delta,delta); -} - -void inflateRect(QRect &rect, int dx, int dy) -{ - rect.setLeft(rect.left()-dx); - rect.setRight(rect.right()+dx); - rect.setTop(rect.top()-dy); - rect.setBottom(rect.bottom()+dy); -} - -QString trimRight(const QString &s) -{ - if (s.isEmpty()) - return s; - int i = s.length()-1; -// while ((i>=0) && ((s[i] == '\r') || (s[i]=='\n') || (s[i] == '\t') || (s[i]==' '))) { - while ((i>=0) && (s[i]<=32)) { - i--; - }; - if (i>=0) { - return s.left(i+1); - } else { - return QString(); - } -} - -bool stringIsBlank(const QString &s) -{ - for (QChar ch:s) { - if (ch != ' ' && ch != '\t') - return false; - } - return true; -} - -QString trimLeft(const QString &s) -{ - if (s.isEmpty()) - return s; - int i=0; -// while ((i(QApplication::instance()); -// //app->setStyleSheet(""); -// return ; -// } -// QStyleFactory styleFactory; -// if (styleFactory.keys().contains(themeName)) { -// QApplication::setStyle(themeName); -// QApplication* app = dynamic_cast(QApplication::instance()); -// app->setStyleSheet(""); -// return; -// } -// QFile f(QString(":/themes/%1/style.qss").arg(themeName)); - -// if (!f.exists()) { -// qDebug()<<"Unable to set stylesheet, file not found\n"; -// } else { -// QApplication::setStyle("Fusion"); -// f.open(QFile::ReadOnly | QFile::Text); -// QTextStream ts(&f); -// dynamic_cast(QApplication::instance())->setStyleSheet(ts.readAll()); -// } -//} - -int compareFileModifiedTime(const QString &filename1, const QString &filename2) -{ - QFileInfo fileInfo1(filename1); - QFileInfo fileInfo2(filename2); - qint64 time1=fileInfo1.lastModified().toMSecsSinceEpoch(); - qint64 time2=fileInfo2.lastModified().toMSecsSinceEpoch(); - if (time1 > time2) - return 1; - if (time1 < time2) - return -1; - return 0; -} - -QString changeFileExt(const QString& filename, QString ext) -{ - QFileInfo fileInfo(filename); - QString suffix = fileInfo.suffix(); - QString name = fileInfo.fileName(); - QString path; - if (!ext.isEmpty() && !ext.startsWith(".")) { - ext = "."+ext; - } - if (fileInfo.path() != ".") { - path = includeTrailingPathDelimiter(fileInfo.path()); - } - if (suffix.isEmpty()) { - return path+filename+ext; - } else { - return path+fileInfo.completeBaseName()+ext; - } -} - QStringList readFileToLines(const QString &fileName) { QFile file(fileName); @@ -609,334 +329,13 @@ QStringList readFileToLines(const QString &fileName) return result; } -void stringsToFile(const QStringList &list, const QString &fileName) +QByteArray readFileToByteArray(const QString &fileName) { QFile file(fileName); - if (file.open(QIODevice::WriteOnly | QIODevice::Truncate)) { - QTextStream stream(&file); - for (QString s:list) { - stream<= QT_VERSION_CHECK(5,15,0) - < parser, int compilerSetIndex) -{ - if (!parser) - return; - // Configure parser - parser->reset(); - //paser->enabled = pSettings-> devCodeCompletion.Enabled; -// CppParser.ParseLocalHeaders := devCodeCompletion.ParseLocalHeaders; -// CppParser.ParseGlobalHeaders := devCodeCompletion.ParseGlobalHeaders; - parser->setEnabled(true); - parser->setParseGlobalHeaders(true); - parser->setParseLocalHeaders(true); - // Set options depending on the current compiler set - // TODO: do this every time OnCompilerSetChanged - if (compilerSetIndex<0) { - compilerSetIndex=pSettings->compilerSets().defaultIndex(); - } - Settings::PCompilerSet compilerSet = pSettings->compilerSets().getSet(compilerSetIndex); - parser->clearIncludePaths(); - if (compilerSet) { - foreach (const QString& file,compilerSet->CppIncludeDirs()) { - parser->addIncludePath(file); - } - foreach (const QString& file,compilerSet->CIncludeDirs()) { - parser->addIncludePath(file); - } - foreach (const QString& file,compilerSet->defaultCppIncludeDirs()) { - parser->addIncludePath(file); - } - foreach (const QString& file,compilerSet->defaultCIncludeDirs()) { - parser->addIncludePath(file); - } - //TODO: Add default include dirs last, just like gcc does - // Set defines - if (parser->language()==ParserLanguage::C) { - for (QString define:compilerSet->CDefines()) { - parser->addHardDefineByLine(define); // predefined constants from -dM -E - } - } else { - for (QString define:compilerSet->CppDefines()) { - parser->addHardDefineByLine(define); // predefined constants from -dM -E - } - } - // add a Red Pand C++ 's own macro - parser->addHardDefineByLine("#define EGE_FOR_AUTO_CODE_COMPLETETION_ONLY"); - // add C/C++ default macro - parser->addHardDefineByLine("#define __FILE__ 1"); - parser->addHardDefineByLine("#define __LINE__ 1"); - parser->addHardDefineByLine("#define __DATE__ 1"); - 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) -{ - int curPosBackup = curPos; - int level = 0; - //todo: skip comment, char and strings - while ((curPos < s.length()) && (curPos >= 0)) { - if (s[curPos] == fromToken) { - level++; - } else if (s[curPos] == toToken) { - level--; - if (level == 0) - return true; - } - curPos += increment; - } - 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<= QT_VERSION_CHECK(5,15,0) - <toUnicode(s,s.length(),&state); - if (state.invalidChars>0) - tmp = QString::fromLocal8Bit(s); - return tmp; -} - -QString linesToText(const QStringList &lines) -{ - return lines.join("\n"); -} - -QString parseMacros(const QString &s) -{ - QString result = s; - Editor *e = pMainWindow->editorList()->getEditor(); - - result.replace("", localizePath(QDir::currentPath())); - result.replace("", localizePath(pSettings->dirs().executable())); - result.replace("", REDPANDA_CPP_VERSION); - result.replace("", localizePath(pSettings->dirs().appDir())); - QDate today = QDate::currentDate(); - QDateTime now = QDateTime::currentDateTime(); - - result.replace("", today.toString("yyyy-MM-dd")); - result.replace("", now.toString("yyyy-MM-dd hh:mm:ss")); - - Settings::PCompilerSet compilerSet = pSettings->compilerSets().defaultSet(); - if (compilerSet) { - // Only provide the first cpp include dir - if (compilerSet->defaultCppIncludeDirs().count()>0) - result.replace("", localizePath(compilerSet->defaultCppIncludeDirs().front())); - else - result.replace("",""); - - // Only provide the first lib dir - if (compilerSet->defaultLibDirs().count()>0) - result.replace("", localizePath(compilerSet->defaultLibDirs().front())); - else - result.replace("",""); - } - - if (e!=nullptr && !e->inProject()) { // Non-project editor macros - result.replace("", extractFileName(changeFileExt(e->filename(),EXECUTABLE_EXT))); - result.replace("", localizePath(changeFileExt(e->filename(),EXECUTABLE_EXT))); - result.replace("", extractFileName(e->filename())); - result.replace("", localizePath(e->filename())); - result.replace("", extractFileName(e->filename())); - result.replace("", localizePath(extractFileDir(e->filename()))); - } else if (pMainWindow->project()) { - result.replace("", extractFileName(pMainWindow->project()->executable())); - result.replace("", localizePath(pMainWindow->project()->executable())); - result.replace("", pMainWindow->project()->name()); - result.replace("", localizePath(pMainWindow->project()->filename())); - result.replace("", extractFileName(pMainWindow->project()->filename())); - result.replace("", localizePath(pMainWindow->project()->directory())); - } else { - result.replace("", ""); - result.replace("", ""); - result.replace("", ""); - result.replace("", ""); - result.replace("", ""); - result.replace("", ""); - } - - // Editor macros - if (e!=nullptr) { - result.replace("", extractFileName(e->filename())); - result.replace("", localizePath(e->filename())); - result.replace("", localizePath(extractFileDir(e->filename()))); - result.replace("", e->wordAtCursor()); - } else { - result.replace("", ""); - result.replace("", ""); - result.replace("", ""); - result.replace("", ""); - } - return result; -} - -void executeFile(const QString &fileName, const QString ¶ms, const QString &workingDir, const QString &tempFile) -{ - ExecutableRunner* runner=new ExecutableRunner( - fileName, - params, - workingDir); - runner->connect(runner, &QThread::finished, - [runner,tempFile](){ - if (!tempFile.isEmpty()) { - QFile::remove(tempFile); - } - runner->deleteLater(); - }); - runner->connect(runner, &Runner::runErrorOccurred, - [](const QString&){ - //todo - }); - runner->setStartConsole(true); - runner->start(); + return QByteArray(); } void stringToFile(const QString &str, const QString &fileName) @@ -948,204 +347,81 @@ void stringToFile(const QString &str, const QString &fileName) } } + +void stringsToFile(const QStringList &list, const QString &fileName) +{ + QFile file(fileName); + if (file.open(QIODevice::WriteOnly | QIODevice::Truncate)) { + QTextStream stream(&file); + for (const QString& s:list) { + stream<= QT_VERSION_CHECK(5,15,0) + <=0) { - return content.mid(i+4); - } - return ""; -} - -bool haveGoodContrast(const QColor& c1, const QColor &c2) { - int lightness1 = qGray(c1.rgb()); - int lightness2 = qGray(c2.rgb()); - return std::abs(lightness1 - lightness2)>=120; -} - - -#ifdef Q_OS_WIN -bool readRegistry(HKEY key,const QByteArray& subKey, const QByteArray& name, QString& value) { - DWORD dataSize; - LONG result; - result = RegGetValueA(key,subKey, - name, RRF_RT_REG_SZ | RRF_RT_REG_MULTI_SZ, - NULL, - NULL, - &dataSize); - if (result!=ERROR_SUCCESS) - return false; - char * buffer = new char[dataSize+10]; - result = RegGetValueA(key,subKey, - name, RRF_RT_REG_SZ | RRF_RT_REG_MULTI_SZ, - NULL, - buffer, - &dataSize); - if (result!=ERROR_SUCCESS) { - delete[] buffer; + QFile fromFile(fromPath); + QFile toFile(toPath); + if (!fromFile.exists()) return false; + if (toFile.exists()) { + if (!overwrite) + return false; + if (!toFile.remove()) + return false; } - value=QString::fromLocal8Bit(buffer); - delete [] buffer; + + if (!fromFile.open(QFile::ReadOnly)) + return false; + if (!toFile.open(QFile::WriteOnly | QFile::Truncate)) + return false; + + int bufferSize=64*1024; + char buffer[bufferSize]; + + while (!fromFile.atEnd()) { + int readed = fromFile.read(buffer,bufferSize); + toFile.write(buffer,readed); + } + toFile.close(); + fromFile.close(); return true; } -#endif - -QList splitByteArrayToLines(const QByteArray &content) -{ - QList 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; -} - -QString localizePath(const QString &path) -{ - QString result = path; - result.replace("/",QDir::separator()); - return result; -} - -float pointToPixel(float point) -{ - return point * screenDPI() / 72; -} - -float pixelToPoint(float pixel) -{ - return pixel * 72 / screenDPI(); -} - - -QStringList splitProcessCommand(const QString &cmd) -{ - QStringList result; - SplitProcessCommandQuoteType quoteType = SplitProcessCommandQuoteType::None; - int i=0; - QString current; - while (iprimaryScreen()->logicalDotsPerInch(); - } - return defaultScreenDPI; -} - -qulonglong stringToHex(const QString &str, bool &isOk) -{ - qulonglong value = str.toULongLong(&isOk,16); - return value; -} - -void setScreenDPI(int dpi) -{ - defaultScreenDPI = dpi; -} void copyFolder(const QString &fromDir, const QString &toDir) { @@ -1187,50 +463,148 @@ void copyFolder(const QString &fromDir, const QString &toDir) } } +QString includeTrailingPathDelimiter(const QString &path) +{ + if (path.endsWith('/') || path.endsWith(QDir::separator())) { + return path; + } else { + return path + "/"; + } +} +QString excludeTrailingPathDelimiter(const QString &path) +{ + int pos = path.length()-1; + while (pos>=0 && (path[pos]=='/' || path[pos]==QDir::separator())) + pos--; + return path.mid(0,pos+1); +} + +QString changeFileExt(const QString& filename, QString ext) +{ + QFileInfo fileInfo(filename); + QString suffix = fileInfo.suffix(); + QString name = fileInfo.fileName(); + QString path; + if (!ext.isEmpty() && !ext.startsWith(".")) { + ext = "."+ext; + } + if (fileInfo.path() != ".") { + path = includeTrailingPathDelimiter(fileInfo.path()); + } + if (suffix.isEmpty()) { + return path+filename+ext; + } else { + return path+fileInfo.completeBaseName()+ext; + } +} + +QString extractRelativePath(const QString &base, const QString &dest) +{ + QFileInfo baseInfo(base); + QDir baseDir; + if (baseInfo.isDir()) { + baseDir = QDir(baseInfo.absoluteFilePath()); + } else { + baseDir = baseInfo.absoluteDir(); + } + return baseDir.relativeFilePath(dest); +} + +QString localizePath(const QString &path) +{ + QString result = path; + result.replace("/",QDir::separator()); + return result; +} + +QString extractFileName(const QString &fileName) +{ + QFileInfo fileInfo(fileName); + return fileInfo.fileName(); +} + +QString extractFileDir(const QString &fileName) +{ + return extractFilePath(fileName); +} + +QString extractFilePath(const QString &filePath) +{ + QFileInfo info(filePath); + return info.path(); +} + +QString extractAbsoluteFilePath(const QString &filePath) +{ + QFileInfo info(filePath); + return info.absoluteFilePath(); +} + +bool isReadOnly(const QString &filename) +{ + return QFile(filename).isWritable(); +} + +int compareFileModifiedTime(const QString &filename1, const QString &filename2) +{ + QFileInfo fileInfo1(filename1); + QFileInfo fileInfo2(filename2); + qint64 time1=fileInfo1.lastModified().toMSecsSinceEpoch(); + qint64 time2=fileInfo2.lastModified().toMSecsSinceEpoch(); + if (time1 > time2) + return 1; + if (time1 < time2) + return -1; + return 0; +} + + +void inflateRect(QRect &rect, int delta) +{ + inflateRect(rect,delta,delta); +} + +void inflateRect(QRect &rect, int dx, int dy) +{ + rect.setLeft(rect.left()-dx); + rect.setRight(rect.right()+dx); + rect.setTop(rect.top()-dy); + rect.setBottom(rect.bottom()+dy); +} + + +static int defaultScreenDPI = -1; + +int screenDPI() +{ + if (defaultScreenDPI<1) { + defaultScreenDPI = qApp->primaryScreen()->logicalDotsPerInch(); + } + return defaultScreenDPI; +} + + +void setScreenDPI(int dpi) +{ + defaultScreenDPI = dpi; +} float pointToPixel(float point, float dpi) { return point * dpi / 72; } -int countLeadingWhitespaceChars(const QString &line) +float pointToPixel(float point) { - int n=0; - while (n32) - break; - n++; - } - return n; + return pointToPixel(point,screenDPI()); } -bool copyFile(const QString &fromPath, const QString &toPath, bool overwrite) +float pixelToPoint(float pixel) { - QFile fromFile(fromPath); - QFile toFile(toPath); - if (!fromFile.exists()) - return false; - if (toFile.exists()) { - if (!overwrite) - return false; - if (!toFile.remove()) - return false; - } - - if (!fromFile.open(QFile::ReadOnly)) - return false; - if (!toFile.open(QFile::WriteOnly | QFile::Truncate)) - return false; - - int bufferSize=64*1024; - char buffer[bufferSize]; - - while (!fromFile.atEnd()) { - int readed = fromFile.read(buffer,bufferSize); - toFile.write(buffer,readed); - } - toFile.close(); - fromFile.close(); - return true; + return pixel * 72 / screenDPI(); } + + + + diff --git a/libs/redpanda_qt_utils/redpanda_utils.h b/libs/redpanda_qt_utils/redpanda_utils.h index 5baef2ea..9796a3c4 100644 --- a/libs/redpanda_qt_utils/redpanda_utils.h +++ b/libs/redpanda_qt_utils/redpanda_utils.h @@ -14,8 +14,8 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -#ifndef QT_UTILS_UTILS_H -#define QT_UTILS_UTILS_H +#ifndef REDPANDA_UTILS_H +#define REDPANDA_UTILS_H #include #include #include @@ -25,88 +25,23 @@ #include #include #include -#include "SimpleIni.h" class QByteArray; class QTextStream; class QTextCodec; -using SimpleIni = CSimpleIniA; -using PSimpleIni = std::shared_ptr; - #define ENCODING_AUTO_DETECT "AUTO" #define ENCODING_UTF8 "UTF-8" #define ENCODING_UTF8_BOM "UTF-8 BOM" #define ENCODING_SYSTEM_DEFAULT "SYSTEM" #define ENCODING_ASCII "ASCII" -enum class FileType{ - CSource, // c source file (.c) - CppSource, // c++ source file (.cpp) - CHeader, // c header (.h) - CppHeader, // c++ header (.hpp) - WindowsResourceSource, // resource source (.res) - Project, //Red Panda C++ Project (.dev) - Text, // text file - Other // any others -}; - enum class FileEndingType { Windows, Linux, Mac };// Windows: CRLF, UNIX: LF, Mac: CR -enum class SearchFileScope { - currentFile, - wholeProject, - openedFiles -}; - -enum AutoSaveTarget { - astCurrentFile, - astAllOpennedFiles, - astAllProjectFiles -}; - -enum AutoSaveStrategy { - assOverwrite, - assAppendUnixTimestamp, - assAppendFormatedTimeStamp -}; - -enum FormatterBraceStyle { - fbsDefault, - fbsAllman, - fbsJava, - fbsKR, - fbsStroustrup, - fbsWitesmith, - fbsVtk, - fbsRatliff, - fbsGNU, - fbsLinux, - fbsHorstmann, - fbs1TBS, - fbsGoogle, - fbsMozilla, - fbsWebkit, - fbsPico, - fbsLisp -}; - -enum FormatterOperatorAlign { - foaNone, - foaType, - foaMiddle, - foaName -}; - -enum FormatterIndentType { - fitSpace, - fitTab -}; - class BaseError{ public: explicit BaseError(const QString& reason); @@ -126,54 +61,36 @@ public: explicit FileError(const QString& reason); }; -typedef void (*LineOutputFunc) (const QString& line); -typedef bool (*CheckAbortFunc) (); -bool isGreenEdition(); - -const QByteArray GuessTextEncoding(const QByteArray& text); +/* text processing utils */ +const QByteArray guessTextEncoding(const QByteArray& text); bool isTextAllAscii(const QByteArray& text); bool isTextAllAscii(const QString& text); -QByteArray runAndGetOutput(const QString& cmd, const QString& workingDir, const QStringList& arguments, - const QByteArray& inputContent = QByteArray(), - bool inheritEnvironment = false, - const QProcessEnvironment& env = QProcessEnvironment() ); - -void executeFile(const QString& fileName, - const QString& params, - const QString& workingDir, - const QString& tempFile); - bool isNonPrintableAsciiChar(char ch); -bool fileExists(const QString& file); -bool fileExists(const QString& dir, const QString& fileName); -bool directoryExists(const QString& file); -bool removeFile(const QString& filename); -QString includeTrailingPathDelimiter(const QString& path); -QString excludeTrailingPathDelimiter(const QString& path); -FileType getFileType(const QString& filename); -QString changeFileExt(const QString& filename, QString ext); -QString extractRelativePath(const QString& base, const QString& dest); -QString genMakePath(const QString& fileName,bool escapeSpaces, bool encloseInQuotes); -QString genMakePath1(const QString& fileName); -QString genMakePath2(const QString& fileName); -QString getCompiledExecutableName(const QString& filename); -void splitStringArguments(const QString& arguments, QStringList& argumentList); -bool programHasConsole(const QString& filename); using LineProcessFunc = std::function; -QStringList readStreamToLines(QTextStream* stream); -void readStreamToLines(QTextStream* stream, LineProcessFunc lineFunc); - QStringList textToLines(const QString& text); void textToLines(const QString& text, LineProcessFunc lineFunc); -QString linesToText(const QStringList& lines); +QString linesToText(const QStringList& lines, const QString& lineBreak="\n"); QList splitByteArrayToLines(const QByteArray& content); -QString parseMacros(const QString& s); +QString trimRight(const QString& s); +QString trimLeft(const QString& s); + +int countLeadingWhitespaceChars(const QString& line); + +bool stringIsBlank(const QString& s); + +QByteArray toByteArray(const QString& s); +QString fromByteArray(const QByteArray& s); + +/* text I/O utils */ + +QStringList readStreamToLines(QTextStream* stream); +void readStreamToLines(QTextStream* stream, LineProcessFunc lineFunc); /** * @brief readFileToLines @@ -183,61 +100,40 @@ QString parseMacros(const QString& s); */ QStringList readFileToLines(const QString& fileName, QTextCodec* codec); QStringList readFileToLines(const QString& fileName); -QByteArray readFileToByteArray(const QString& fileName); void readFileToLines(const QString& fileName, QTextCodec* codec, LineProcessFunc lineFunc); + +QByteArray readFileToByteArray(const QString& fileName); + void stringsToFile(const QStringList& list, const QString& fileName); void stringToFile(const QString& str, const QString& fileName); -int countLeadingWhitespaceChars(const QString& line); -void decodeKey(int combinedKey, int& key, Qt::KeyboardModifiers& modifiers); -void inflateRect(QRect& rect, int delta); -void inflateRect(QRect& rect, int dx, int dy); -QString trimRight(const QString& s); -QString trimLeft(const QString& s); -bool stringIsBlank(const QString& s); -int compareFileModifiedTime(const QString& filename1, const QString& filename2); -QByteArray getHTTPBody(const QByteArray& content); -bool haveGoodContrast(const QColor& c1, const QColor &c2); -qulonglong stringToHex(const QString& str, bool &isOk); +/* File I/O utils */ +bool fileExists(const QString& file); +bool fileExists(const QString& dir, const QString& fileName); +bool directoryExists(const QString& file); +bool removeFile(const QString& filename); +void copyFolder(const QString &fromDir, const QString& toDir); +bool copyFile(const QString &fromFile, const QString& toFile, bool overwrite); -//void changeTheme(const QString& themeName); - -bool findComplement(const QString& s, - const QChar& fromToken, - const QChar& toToken, - int& curPos, - int increment); -void logToFile(const QString& s, const QString& filename, bool append=true); +QString includeTrailingPathDelimiter(const QString& path); +QString excludeTrailingPathDelimiter(const QString& path); +QString changeFileExt(const QString& filename, QString ext); QString localizePath(const QString& path); + +QString extractRelativePath(const QString& base, const QString& dest); QString extractFileName(const QString& fileName); QString extractFileDir(const QString& fileName); QString extractFilePath(const QString& filePath); QString extractAbsoluteFilePath(const QString& filePath); -QString getSizeString(int size); + bool isReadOnly(const QString& filename); +int compareFileModifiedTime(const QString& filename1, const QString& filename2); -QByteArray toByteArray(const QString& s); -QString fromByteArray(const QByteArray& s); - -int getNewFileNumber(); - -enum class SplitProcessCommandQuoteType { - None, - Single, - Double -}; - -QStringList splitProcessCommand(const QString& cmd); - - -#ifdef Q_OS_WIN -bool readRegistry(HKEY key,const QByteArray& subKey, const QByteArray& name, QString& value); -#endif - -class CppParser; -void resetCppParser(std::shared_ptr parser, int compilerSetIndex=-1); +/* UI utils */ +void inflateRect(QRect& rect, int delta); +void inflateRect(QRect& rect, int dx, int dy); int screenDPI(); void setScreenDPI(int dpi); @@ -245,8 +141,7 @@ float pointToPixel(float point); float pointToPixel(float point, float dpi); float pixelToPoint(float pixel); -void copyFolder(const QString &fromDir, const QString& toDir); -bool copyFile(const QString &fromFile, const QString& toFile, bool overwrite); +void decodeKey(int combinedKey, int& key, Qt::KeyboardModifiers& modifiers); /**