diff --git a/src/CutterApplication.cpp b/src/CutterApplication.cpp index 6ec59a4b..a34591d9 100644 --- a/src/CutterApplication.cpp +++ b/src/CutterApplication.cpp @@ -21,13 +21,13 @@ #include #include #ifdef Q_OS_WIN -#include +# include #endif // Q_OS_WIN #include #if CUTTER_RZGHIDRA_STATIC -#include +# include #endif CutterApplication::CutterApplication(int &argc, char **argv) : QApplication(argc, argv) @@ -38,7 +38,8 @@ CutterApplication::CutterApplication(int &argc, char **argv) : QApplication(argc setAttribute(Qt::AA_UseHighDpiPixmaps); setLayoutDirection(Qt::LeftToRight); - // WARN!!! Put initialization code below this line. Code above this line is mandatory to be run First + // WARN!!! Put initialization code below this line. Code above this line is mandatory to be run + // First #ifdef Q_OS_WIN // Hack to force Cutter load internet connection related DLL's @@ -62,10 +63,9 @@ CutterApplication::CutterApplication(int &argc, char **argv) : QApplication(argc qWarning() << "Cannot load Incosolata-Regular font."; } - // Set QString codec to UTF-8 QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8")); -#if QT_VERSION < QT_VERSION_CHECK(5,0,0) +#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8")); QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8")); #endif @@ -82,9 +82,10 @@ CutterApplication::CutterApplication(int &argc, char **argv) : QApplication(argc msg.setIcon(QMessageBox::Critical); msg.setStandardButtons(QMessageBox::Yes | QMessageBox::No); msg.setWindowTitle(QObject::tr("Version mismatch!")); - msg.setText(QString( - QObject::tr("The version used to compile Cutter (%1) does not match the binary version of rizin (%2). This could result in unexpected behaviour. Are you sure you want to continue?")).arg( - localVersion, rzversion)); + msg.setText(QString(QObject::tr("The version used to compile Cutter (%1) does not match " + "the binary version of rizin (%2). This could result in " + "unexpected behaviour. Are you sure you want to continue?")) + .arg(localVersion, rzversion)); if (msg.exec() == QMessageBox::No) { std::exit(1); } @@ -134,7 +135,8 @@ CutterApplication::CutterApplication(int &argc, char **argv) : QApplication(argc if (clOptions.args.empty()) { // check if this is the first execution of Cutter in this computer - // Note: the execution after the preferences been reset, will be considered as first-execution + // Note: the execution after the preferences been reset, will be considered as + // first-execution if (Config()->isFirstExecution()) { mainWindow->displayWelcomeDialog(); } @@ -144,14 +146,14 @@ CutterApplication::CutterApplication(int &argc, char **argv) : QApplication(argc mainWindow->openNewFile(clOptions.fileOpenOptions, askOptions); } - #ifdef APPIMAGE { auto appdir = QDir(QCoreApplication::applicationDirPath()); // appdir/bin appdir.cdUp(); // appdir auto sleighHome = appdir; - sleighHome.cd("share/rizin/plugins/rz_ghidra_sleigh"); // appdir/share/rizin/plugins/rz_ghidra_sleigh + sleighHome.cd( + "share/rizin/plugins/rz_ghidra_sleigh"); // appdir/share/rizin/plugins/rz_ghidra_sleigh Core()->setConfig("ghidra.sleighhome", sleighHome.absolutePath()); auto jsdecHome = appdir; @@ -167,11 +169,13 @@ CutterApplication::CutterApplication(int &argc, char **argv) : QApplication(argc rzprefix.cd("Resources"); // Contents/Resources/rz auto sleighHome = rzprefix; - sleighHome.cd("share/rizin/plugins/rz_ghidra_sleigh"); // Contents/Resources/rz/share/rizin/plugins/rz_ghidra_sleigh + sleighHome.cd( + "share/rizin/plugins/rz_ghidra_sleigh"); // Contents/Resources/rz/share/rizin/plugins/rz_ghidra_sleigh Core()->setConfig("ghidra.sleighhome", sleighHome.absolutePath()); auto jsdecHome = rzprefix; - jsdecHome.cd("share/rizin/plugins/jsdec"); // Contents/Resources/rz/share/rizin/plugins/jsdec + jsdecHome.cd( + "share/rizin/plugins/jsdec"); // Contents/Resources/rz/share/rizin/plugins/jsdec qputenv("JSDEC_HOME", jsdecHome.absolutePath().toLocal8Bit()); } #endif @@ -221,7 +225,7 @@ bool CutterApplication::event(QEvent *e) // We already dropped a file in macOS, let's spawn another instance // (Like the File -> Open) QString fileName = openEvent->file(); - launchNewInstance({fileName}); + launchNewInstance({ fileName }); } else { QString fileName = openEvent->file(); m_FileAlreadyDropped = true; @@ -241,8 +245,8 @@ bool CutterApplication::loadTranslations() if (language == QStringLiteral("en") || language.startsWith(QStringLiteral("en-"))) { return true; } - const auto &allLocales = QLocale::matchingLocales(QLocale::AnyLanguage, QLocale::AnyScript, - QLocale::AnyCountry); + const auto &allLocales = + QLocale::matchingLocales(QLocale::AnyLanguage, QLocale::AnyScript, QLocale::AnyCountry); bool cutterTrLoaded = false; @@ -259,7 +263,8 @@ bool CutterApplication::loadTranslations() const QStringList &cutterTrPaths = Cutter::getTranslationsDirectories(); for (const auto &trPath : cutterTrPaths) { - if (trCutter && trCutter->load(it, QLatin1String("cutter"), QLatin1String("_"), trPath)) { + if (trCutter + && trCutter->load(it, QLatin1String("cutter"), QLatin1String("_"), trPath)) { installTranslator(trCutter); cutterTrLoaded = true; trCutter = nullptr; @@ -299,52 +304,50 @@ bool CutterApplication::parseCommandLineOptions() QCommandLineParser cmd_parser; cmd_parser.setApplicationDescription( - QObject::tr("A Qt and C++ GUI for rizin reverse engineering framework")); + QObject::tr("A Qt and C++ GUI for rizin reverse engineering framework")); cmd_parser.addHelpOption(); cmd_parser.addVersionOption(); cmd_parser.addPositionalArgument("filename", QObject::tr("Filename to open.")); - QCommandLineOption analOption({"A", "analysis"}, - QObject::tr("Automatically open file and optionally start analysis. " - "Needs filename to be specified. May be a value between 0 and 2:" - " 0 = no analysis, 1 = aaa, 2 = aaaa (experimental)"), - QObject::tr("level")); + QCommandLineOption analOption( + { "A", "analysis" }, + QObject::tr("Automatically open file and optionally start analysis. " + "Needs filename to be specified. May be a value between 0 and 2:" + " 0 = no analysis, 1 = aaa, 2 = aaaa (experimental)"), + QObject::tr("level")); cmd_parser.addOption(analOption); - QCommandLineOption formatOption({"F", "format"}, + QCommandLineOption formatOption({ "F", "format" }, QObject::tr("Force using a specific file format (bin plugin)"), QObject::tr("name")); cmd_parser.addOption(formatOption); - QCommandLineOption baddrOption({"B", "base"}, + QCommandLineOption baddrOption({ "B", "base" }, QObject::tr("Load binary at a specific base address"), QObject::tr("base address")); cmd_parser.addOption(baddrOption); - QCommandLineOption scriptOption("i", - QObject::tr("Run script file"), - QObject::tr("file")); + QCommandLineOption scriptOption("i", QObject::tr("Run script file"), QObject::tr("file")); cmd_parser.addOption(scriptOption); - QCommandLineOption writeModeOption({"w", "writemode"}, + QCommandLineOption writeModeOption({ "w", "writemode" }, QObject::tr("Open file in write mode")); cmd_parser.addOption(writeModeOption); - - QCommandLineOption pythonHomeOption("pythonhome", - QObject::tr("PYTHONHOME to use for embedded python interpreter"), - "PYTHONHOME"); + QCommandLineOption pythonHomeOption( + "pythonhome", QObject::tr("PYTHONHOME to use for embedded python interpreter"), + "PYTHONHOME"); cmd_parser.addOption(pythonHomeOption); - QCommandLineOption disableRedirectOption("no-output-redirect", - QObject::tr("Disable output redirection." - " Some of the output in console widget will not be visible." - " Use this option when debuging a crash or freeze and output " - " redirection is causing some messages to be lost.")); + QCommandLineOption disableRedirectOption( + "no-output-redirect", + QObject::tr("Disable output redirection." + " Some of the output in console widget will not be visible." + " Use this option when debuging a crash or freeze and output " + " redirection is causing some messages to be lost.")); cmd_parser.addOption(disableRedirectOption); - QCommandLineOption disablePlugins("no-plugins", - QObject::tr("Do not load plugins")); + QCommandLineOption disablePlugins("no-plugins", QObject::tr("Do not load plugins")); cmd_parser.addOption(disablePlugins); QCommandLineOption disableCutterPlugins("no-cutter-plugins", @@ -352,7 +355,7 @@ bool CutterApplication::parseCommandLineOptions() cmd_parser.addOption(disableCutterPlugins); QCommandLineOption disableRizinPlugins("no-rizin-plugins", - QObject::tr("Do not load rizin plugins")); + QObject::tr("Do not load rizin plugins")); cmd_parser.addOption(disableRizinPlugins); cmd_parser.process(*this); @@ -366,7 +369,9 @@ bool CutterApplication::parseCommandLineOptions() if (!analLevelSpecified || analLevel < 0 || analLevel > 2) { fprintf(stderr, "%s\n", - QObject::tr("Invalid Analysis Level. May be a value between 0 and 2.").toLocal8Bit().constData()); + QObject::tr("Invalid Analysis Level. May be a value between 0 and 2.") + .toLocal8Bit() + .constData()); return false; } switch (analLevel) { @@ -384,7 +389,9 @@ bool CutterApplication::parseCommandLineOptions() if (opts.args.empty() && opts.analLevel != AutomaticAnalysisLevel::Ask) { fprintf(stderr, "%s\n", - QObject::tr("Filename must be specified to start analysis automatically.").toLocal8Bit().constData()); + QObject::tr("Filename must be specified to start analysis automatically.") + .toLocal8Bit() + .constData()); return false; } @@ -406,10 +413,10 @@ bool CutterApplication::parseCommandLineOptions() opts.fileOpenOptions.analCmd = {}; break; case AutomaticAnalysisLevel::AAA: - opts.fileOpenOptions.analCmd = { {"aaa", "Auto analysis"} }; + opts.fileOpenOptions.analCmd = { { "aaa", "Auto analysis" } }; break; case AutomaticAnalysisLevel::AAAA: - opts.fileOpenOptions.analCmd = { {"aaaa", "Auto analysis (experimental)"} }; + opts.fileOpenOptions.analCmd = { { "aaaa", "Auto analysis (experimental)" } }; break; } opts.fileOpenOptions.script = cmd_parser.value(scriptOption); @@ -439,7 +446,6 @@ bool CutterApplication::parseCommandLineOptions() return true; } - void CutterProxyStyle::polish(QWidget *widget) { QProxyStyle::polish(widget); diff --git a/src/CutterApplication.h b/src/CutterApplication.h index 31c910aa..cf2fd4d0 100644 --- a/src/CutterApplication.h +++ b/src/CutterApplication.h @@ -8,11 +8,10 @@ #include "core/MainWindow.h" -enum class AutomaticAnalysisLevel { - Ask, None, AAA, AAAA -}; +enum class AutomaticAnalysisLevel { Ask, None, AAA, AAAA }; -struct CutterCommandLineOptions { +struct CutterCommandLineOptions +{ QStringList args; AutomaticAnalysisLevel analLevel = AutomaticAnalysisLevel::Ask; InitialOptions fileOpenOptions; @@ -30,12 +29,10 @@ public: CutterApplication(int &argc, char **argv); ~CutterApplication(); - MainWindow *getMainWindow() - { - return mainWindow; - } + MainWindow *getMainWindow() { return mainWindow; } void launchNewInstance(const QStringList &args = {}); + protected: bool event(QEvent *e); @@ -50,13 +47,13 @@ private: * @return false if options have error */ bool parseCommandLineOptions(); + private: bool m_FileAlreadyDropped; MainWindow *mainWindow; CutterCommandLineOptions clOptions; }; - /** * @brief CutterProxyStyle is used to force shortcuts displaying in context menu */ diff --git a/src/Main.cpp b/src/Main.cpp index e47dfc0a..15e99e58 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -10,7 +10,6 @@ #include #include - /** * @brief Attempt to connect to a parent console and configure outputs. * @@ -51,7 +50,6 @@ static void connectToConsole() } #endif - int main(int argc, char *argv[]) { #ifdef CUTTER_ENABLE_CRASH_REPORTS @@ -77,12 +75,14 @@ int main(int argc, char *argv[]) Cutter::initializeSettings(); - QCoreApplication::setAttribute(Qt::AA_ShareOpenGLContexts); // needed for QtWebEngine inside Plugins + QCoreApplication::setAttribute( + Qt::AA_ShareOpenGLContexts); // needed for QtWebEngine inside Plugins #ifdef Q_OS_WIN QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); - #if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0) - QGuiApplication::setHighDpiScaleFactorRoundingPolicy(Qt::HighDpiScaleFactorRoundingPolicy::PassThrough); - #endif +# if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0) + QGuiApplication::setHighDpiScaleFactorRoundingPolicy( + Qt::HighDpiScaleFactorRoundingPolicy::PassThrough); +# endif #endif CutterApplication a(argc, argv); @@ -93,12 +93,13 @@ int main(int argc, char *argv[]) #if CUTTER_UPDATE_WORKER_AVAILABLE UpdateWorker *updateWorker = new UpdateWorker; QObject::connect(updateWorker, &UpdateWorker::checkComplete, - [=](const QVersionNumber &version, const QString & error) { - if (error.isEmpty() && version > UpdateWorker::currentVersionNumber()) { - updateWorker->showUpdateDialog(true); - } - updateWorker->deleteLater(); - }); + [=](const QVersionNumber &version, const QString &error) { + if (error.isEmpty() + && version > UpdateWorker::currentVersionNumber()) { + updateWorker->showUpdateDialog(true); + } + updateWorker->deleteLater(); + }); updateWorker->checkCurrentVersion(7000); #endif } diff --git a/src/bindings/bindings.h b/src/bindings/bindings.h index 19014a4b..b05aa384 100644 --- a/src/bindings/bindings.h +++ b/src/bindings/bindings.h @@ -11,4 +11,4 @@ #include "../plugins/CutterPlugin.h" #include "../menus/AddressableItemContextMenu.h" -#endif //CUTTER_BINDINGS_H +#endif // CUTTER_BINDINGS_H diff --git a/src/common/AddressableItemModel.cpp b/src/common/AddressableItemModel.cpp index 3da649a4..d36fa594 100644 --- a/src/common/AddressableItemModel.cpp +++ b/src/common/AddressableItemModel.cpp @@ -4,8 +4,8 @@ #include AddressableFilterProxyModel::AddressableFilterProxyModel(AddressableItemModelI *sourceModel, - QObject *parent) : - AddressableItemModel(parent) + QObject *parent) + : AddressableItemModel(parent) { setSourceModel(sourceModel); addressableSourceModel = sourceModel; diff --git a/src/common/AddressableItemModel.h b/src/common/AddressableItemModel.h index 1eb704ed..37c02975 100644 --- a/src/common/AddressableItemModel.h +++ b/src/common/AddressableItemModel.h @@ -17,17 +17,22 @@ public: * @param index item intex * @return Item name or empty QString if item doesn't have short descriptive name. */ - virtual QString name(const QModelIndex &index) const { Q_UNUSED(index) return QString(); } + virtual QString name(const QModelIndex &index) const + { + Q_UNUSED(index) + return QString(); + } virtual QAbstractItemModel *asItemModel() = 0; }; -template -class CUTTER_EXPORT AddressableItemModel : public ParentModel, public AddressableItemModelI +template +class CUTTER_EXPORT AddressableItemModel : public ParentModel, public AddressableItemModelI { - static_assert (std::is_base_of::value, - "ParentModel needs to inherit from QAbstractItemModel"); + static_assert(std::is_base_of::value, + "ParentModel needs to inherit from QAbstractItemModel"); + public: - explicit AddressableItemModel(QObject *parent = nullptr) : ParentModel(parent) {} + explicit AddressableItemModel(QObject *parent = nullptr) : ParentModel(parent) {} virtual ~AddressableItemModel() {} QAbstractItemModel *asItemModel() { return this; } }; @@ -35,12 +40,14 @@ public: class CUTTER_EXPORT AddressableFilterProxyModel : public AddressableItemModel { using ParentClass = AddressableItemModel; + public: AddressableFilterProxyModel(AddressableItemModelI *sourceModel, QObject *parent); RVA address(const QModelIndex &index) const override; QString name(const QModelIndex &) const override; void setSourceModel(AddressableItemModelI *sourceModel); + private: void setSourceModel(QAbstractItemModel *sourceModel) override; // Don't use this directly AddressableItemModelI *addressableSourceModel; diff --git a/src/common/AnalTask.cpp b/src/common/AnalTask.cpp index b4263b22..81cfecd7 100644 --- a/src/common/AnalTask.cpp +++ b/src/common/AnalTask.cpp @@ -6,14 +6,9 @@ #include #include -AnalTask::AnalTask() : - AsyncTask() -{ -} +AnalTask::AnalTask() : AsyncTask() {} -AnalTask::~AnalTask() -{ -} +AnalTask::~AnalTask() {} void AnalTask::interrupt() { @@ -21,7 +16,8 @@ void AnalTask::interrupt() rz_cons_singleton()->context->breaked = true; } -QString AnalTask::getTitle() { +QString AnalTask::getTitle() +{ // If no file is loaded we consider it's Initial Analysis QJsonArray openedFiles = Core()->getOpenedFiles(); if (!openedFiles.size()) { @@ -36,7 +32,6 @@ void AnalTask::runTask() if (options.writeEnabled) { perms |= RZ_PERM_W; emit Core()->ioModeChanged(); - } // Demangle (must be before file Core()->loadFile) @@ -47,13 +42,9 @@ void AnalTask::runTask() if (!openedFiles.size() && options.filename.length()) { log(tr("Loading the file...")); openFailed = false; - bool fileLoaded = Core()->loadFile(options.filename, - options.binLoadAddr, - options.mapAddr, - perms, - options.useVA, - options.loadBinInfo, - options.forceBinPlugin); + bool fileLoaded = + Core()->loadFile(options.filename, options.binLoadAddr, options.mapAddr, perms, + options.useVA, options.loadBinInfo, options.forceBinPlugin); if (!fileLoaded) { // Something wrong happened, fallback to open dialog openFailed = true; diff --git a/src/common/AnalTask.h b/src/common/AnalTask.h index eb9044a9..305d8fc2 100644 --- a/src/common/AnalTask.h +++ b/src/common/AnalTask.h @@ -19,11 +19,11 @@ public: QString getTitle() override; - void setOptions(const InitialOptions &options) { this->options = options; } + void setOptions(const InitialOptions &options) { this->options = options; } void interrupt() override; - bool getOpenFileFailed() { return openFailed; } + bool getOpenFileFailed() { return openFailed; } protected: void runTask() override; diff --git a/src/common/AsyncTask.cpp b/src/common/AsyncTask.cpp index 10014622..7e9ddf91 100644 --- a/src/common/AsyncTask.cpp +++ b/src/common/AsyncTask.cpp @@ -1,9 +1,7 @@ #include "AsyncTask.h" -AsyncTask::AsyncTask() - : QObject(nullptr), - QRunnable() +AsyncTask::AsyncTask() : QObject(nullptr), QRunnable() { setAutoDelete(false); running = false; @@ -64,15 +62,12 @@ void AsyncTask::log(QString s) emit logChanged(logBuffer); } -AsyncTaskManager::AsyncTaskManager(QObject *parent) - : QObject(parent) +AsyncTaskManager::AsyncTaskManager(QObject *parent) : QObject(parent) { threadPool = new QThreadPool(this); } -AsyncTaskManager::~AsyncTaskManager() -{ -} +AsyncTaskManager::~AsyncTaskManager() {} void AsyncTaskManager::start(AsyncTask::Ptr task) { diff --git a/src/common/AsyncTask.h b/src/common/AsyncTask.h index 2348d90d..cda92edc 100644 --- a/src/common/AsyncTask.h +++ b/src/common/AsyncTask.h @@ -13,7 +13,7 @@ class AsyncTaskManager; -class CUTTER_EXPORT AsyncTask : public QObject, public QRunnable +class CUTTER_EXPORT AsyncTask : public QObject, public QRunnable { Q_OBJECT @@ -30,17 +30,17 @@ public: void wait(); bool wait(int timeout); virtual void interrupt(); - bool isInterrupted() { return interrupted; } - bool isRunning() { return running; } + bool isInterrupted() { return interrupted; } + bool isRunning() { return running; } - const QString &getLog() { return logBuffer; } - const QElapsedTimer &getTimer() { return timer; } - qint64 getElapsedTime() { return timer.isValid() ? timer.elapsed() : 0; } + const QString &getLog() { return logBuffer; } + const QElapsedTimer &getTimer() { return timer; } + qint64 getElapsedTime() { return timer.isValid() ? timer.elapsed() : 0; } - virtual QString getTitle() { return QString(); } + virtual QString getTitle() { return QString(); } protected: - virtual void runTask() =0; + virtual void runTask() = 0; void log(QString s); @@ -78,5 +78,4 @@ signals: void tasksChanged(); }; - -#endif //ASYNCTASK_H \ No newline at end of file +#endif // ASYNCTASK_H \ No newline at end of file diff --git a/src/common/BasicBlockHighlighter.cpp b/src/common/BasicBlockHighlighter.cpp index 1917707f..f81b336b 100644 --- a/src/common/BasicBlockHighlighter.cpp +++ b/src/common/BasicBlockHighlighter.cpp @@ -1,8 +1,6 @@ #include "BasicBlockHighlighter.h" -BasicBlockHighlighter::BasicBlockHighlighter() -{ -} +BasicBlockHighlighter::BasicBlockHighlighter() {} BasicBlockHighlighter::~BasicBlockHighlighter() { @@ -41,7 +39,7 @@ BasicBlock *BasicBlockHighlighter::getBasicBlock(RVA address) it = bbMap.find(address); if (it != bbMap.end()) { - return it->second; + return it->second; } return nullptr; diff --git a/src/common/BasicBlockHighlighter.h b/src/common/BasicBlockHighlighter.h index 53f44032..fc84b32a 100644 --- a/src/common/BasicBlockHighlighter.h +++ b/src/common/BasicBlockHighlighter.h @@ -6,12 +6,13 @@ class BasicBlockHighlighter; #include "Cutter.h" #include -struct BasicBlock { +struct BasicBlock +{ RVA address; QColor color; }; -typedef std::map::iterator BasicBlockIt; +typedef std::map::iterator BasicBlockIt; class BasicBlockHighlighter { @@ -24,7 +25,7 @@ public: BasicBlock *getBasicBlock(RVA address); private: - std::map bbMap; + std::map bbMap; }; -#endif // BASICBLOCKHIGHLIGHTER_H +#endif // BASICBLOCKHIGHLIGHTER_H diff --git a/src/common/BasicInstructionHighlighter.cpp b/src/common/BasicInstructionHighlighter.cpp index ba363710..152a87b8 100644 --- a/src/common/BasicInstructionHighlighter.cpp +++ b/src/common/BasicInstructionHighlighter.cpp @@ -24,13 +24,13 @@ void BasicInstructionHighlighter::clear(RVA address, RVA size) if (!addrs.empty()) { const BasicInstruction &prev = biMap[addrs.front()]; if (prev.address < address && prev.address + prev.size > address) { - newInstructions.push_back({prev.address, address - prev.address, prev.color}); + newInstructions.push_back({ prev.address, address - prev.address, prev.color }); } const BasicInstruction &next = biMap[addrs.back()]; if (next.address < address + size && next.address + next.size > address + size) { const RVA offset = address + size - next.address; - newInstructions.push_back({next.address + offset, next.size - offset, next.color}); + newInstructions.push_back({ next.address + offset, next.size - offset, next.color }); } } @@ -41,7 +41,7 @@ void BasicInstructionHighlighter::clear(RVA address, RVA size) } } - for ( BasicInstruction newInstr : newInstructions) { + for (BasicInstruction newInstr : newInstructions) { biMap[newInstr.address] = newInstr; } } @@ -52,7 +52,7 @@ void BasicInstructionHighlighter::clear(RVA address, RVA size) void BasicInstructionHighlighter::highlight(RVA address, RVA size, QColor color) { clear(address, size); - biMap[address] = {address, size, color}; + biMap[address] = { address, size, color }; } /** diff --git a/src/common/BasicInstructionHighlighter.h b/src/common/BasicInstructionHighlighter.h index aecdeb1f..5037e180 100644 --- a/src/common/BasicInstructionHighlighter.h +++ b/src/common/BasicInstructionHighlighter.h @@ -5,7 +5,8 @@ #include #include -struct BasicInstruction { +struct BasicInstruction +{ RVA address; RVA size; QColor color; diff --git a/src/common/BinaryTrees.h b/src/common/BinaryTrees.h index 56fef37b..d229736b 100644 --- a/src/common/BinaryTrees.h +++ b/src/common/BinaryTrees.h @@ -11,13 +11,13 @@ #include #include - /** - * Not really a segment tree for storing segments as referred in academic literature. Can be considered a - * full, almost perfect, augmented binary tree. In the context of competitive programming often called segment tree. + * Not really a segment tree for storing segments as referred in academic literature. Can be + * considered a full, almost perfect, augmented binary tree. In the context of competitive + * programming often called segment tree. * - * Child classes are expected to implement updateFromChildren(NodeType&parent, NodeType& left, NodeType& right) - * method which calculates inner node values from children nodes. + * Child classes are expected to implement updateFromChildren(NodeType&parent, NodeType& left, + * NodeType& right) method which calculates inner node values from children nodes. * * \tparam NodeTypeT type of each tree element * \tparam FinalType final child class used for curiously recurring template pattern @@ -33,11 +33,7 @@ public: * @brief Create tree with \a size leaves. * @param size number of leaves in the tree */ - explicit SegmentTreeBase(size_t size) - : size(size) - , nodeCount(2 * size) - , nodes(nodeCount) - {} + explicit SegmentTreeBase(size_t size) : size(size), nodeCount(2 * size), nodes(nodeCount) {} /** * @brief Create a tree with given size and initial value. @@ -46,38 +42,23 @@ public: * @param size number of leaves * @param initialValue initial leave value */ - SegmentTreeBase(size_t size, const NodeType &initialValue) - : SegmentTreeBase(size) + SegmentTreeBase(size_t size, const NodeType &initialValue) : SegmentTreeBase(size) { init(initialValue); } + protected: // Curiously recurring template pattern - FinalType &This() - { - return static_cast(*this); - } + FinalType &This() { return static_cast(*this); } // Curiously recurring template pattern - const FinalType &This() const - { - return static_cast(*this); - } + const FinalType &This() const { return static_cast(*this); } - size_t leavePositionToIndex(NodePosition pos) const - { - return pos - size; - } + size_t leavePositionToIndex(NodePosition pos) const { return pos - size; } - NodePosition leaveIndexToPosition(size_t index) const - { - return index + size; - } + NodePosition leaveIndexToPosition(size_t index) const { return index + size; } - bool isLeave(NodePosition position) const - { - return position >= size; - } + bool isLeave(NodePosition position) const { return position >= size; } /** * @brief Calculate inner node values from leaves. @@ -111,6 +92,7 @@ template class PointSetSegmentTree : public SegmentTreeBase { using BaseType = SegmentTreeBase; + public: using BaseType::BaseType; @@ -125,7 +107,8 @@ public: this->nodes[pos] = value; while (pos > 1) { auto parrent = pos >> 1; - this->This().updateFromChildren(this->nodes[parrent], this->nodes[pos], this->nodes[pos ^ 1]); + this->This().updateFromChildren(this->nodes[parrent], this->nodes[pos], + this->nodes[pos ^ 1]); pos = parrent; } } @@ -141,6 +124,7 @@ public: class PointSetMinTree : public PointSetSegmentTree { using BaseType = PointSetSegmentTree; + public: using NodeType = int; @@ -159,16 +143,15 @@ public: */ int rightMostLessThan(size_t position, int value) { - auto isGood = [&](size_t pos) { - return nodes[pos] < value; - }; + auto isGood = [&](size_t pos) { return nodes[pos] < value; }; // right side exclusive range [l;r) size_t goodSubtree = 0; for (size_t l = leaveIndexToPosition(0), r = leaveIndexToPosition(position + 1); l < r; - l >>= 1, r >>= 1) { + l >>= 1, r >>= 1) { if (l & 1) { if (isGood(l)) { - // mark subtree as good but don't stop yet, there might be something good further to the right + // mark subtree as good but don't stop yet, there might be something good + // further to the right goodSubtree = l; } ++l; @@ -202,13 +185,11 @@ public: */ int leftMostLessThan(size_t position, int value) { - auto isGood = [&](size_t pos) { - return nodes[pos] < value; - }; + auto isGood = [&](size_t pos) { return nodes[pos] < value; }; // right side exclusive range [l;r) size_t goodSubtree = 0; for (size_t l = leaveIndexToPosition(position), r = leaveIndexToPosition(size); l < r; - l >>= 1, r >>= 1) { + l >>= 1, r >>= 1) { if (l & 1) { if (isGood(l)) { goodSubtree = l; @@ -220,7 +201,8 @@ public: --r; if (isGood(r)) { goodSubtree = r; - // mark subtree as good but don't stop yet, there might be something good further to the left + // mark subtree as good but don't stop yet, there might be something good + // further to the left } } } @@ -241,28 +223,28 @@ public: /** * \brief Tree that supports lazily applying an operation to range. * - * Each inner node has a promise value describing an operation that needs to be applied to corresponding subtree. + * Each inner node has a promise value describing an operation that needs to be applied to + * corresponding subtree. * - * Child classes are expected to implement to pushDown(size_t nodePosition) method. Which applies the applies the - * operation stored in \a promise for nodePosition to the direct children nodes. + * Child classes are expected to implement to pushDown(size_t nodePosition) method. Which applies + * the applies the operation stored in \a promise for nodePosition to the direct children nodes. * * \tparam NodeType type of tree nodes * \tparam PromiseType type describing operation that needs to be applied to subtree * \tparam FinalType child class type for CRTP. See SegmentTreeBase */ -template +template class LazySegmentTreeBase : public SegmentTreeBase { using BaseType = SegmentTreeBase; + public: /** * @param size Number of tree leaves. * @param neutralPromise Promise value that doesn't modify tree nodes. */ LazySegmentTreeBase(size_t size, const PromiseType &neutralPromise) - : BaseType(size) - , neutralPromiseElement(neutralPromise) - , promise(size, neutralPromise) + : BaseType(size), neutralPromiseElement(neutralPromise), promise(size, neutralPromise) { h = 0; size_t v = size; @@ -324,7 +306,8 @@ protected: while (p > 1) { auto parent = p >> 1; if (promise[parent] == neutralPromiseElement) { - This().updateFromChildren(this->nodes[parent], this->nodes[p & ~size_t(1)], this->nodes[p | 1]); + This().updateFromChildren(this->nodes[parent], this->nodes[p & ~size_t(1)], + this->nodes[p | 1]); } p = parent; } @@ -337,19 +320,16 @@ protected: std::vector promise; }; - /** * @brief Structure supporting range assignment and range maximum operations. */ class RangeAssignMaxTree : public LazySegmentTreeBase { using BaseType = LazySegmentTreeBase; + public: using ValueType = int; - RangeAssignMaxTree(size_t size, ValueType initialValue) - : BaseType(size, initialValue, 0) - { - } + RangeAssignMaxTree(size_t size, ValueType initialValue) : BaseType(size, initialValue, 0) {} void updateFromChildren(NodeType &parent, const NodeType &left, const NodeType &right) { diff --git a/src/common/BugReporting.cpp b/src/common/BugReporting.cpp index 1bee80c1..b5ece72e 100644 --- a/src/common/BugReporting.cpp +++ b/src/common/BugReporting.cpp @@ -9,11 +9,9 @@ void openIssue() { QString url, osInfo, format, arch, type; - //Pull in info needed for git issue - osInfo = QSysInfo::productType() + " " + - (QSysInfo::productVersion() == "unknown" - ? "" - : QSysInfo::productVersion()); + // Pull in info needed for git issue + osInfo = QSysInfo::productType() + " " + + (QSysInfo::productVersion() == "unknown" ? "" : QSysInfo::productVersion()); QJsonDocument docu = Core()->getFileInfo(); QJsonObject coreObj = docu.object()["core"].toObject(); QJsonObject binObj = docu.object()["bin"].toObject(); @@ -30,16 +28,18 @@ void openIssue() arch = "N/A"; type = "N/A"; } - url = - "https://github.com/rizinorg/cutter/issues/new?&body=**Environment information**\n* Operating System: " - + osInfo + "\n* Cutter version: " + CUTTER_VERSION_FULL + - "\n* File format: " + format + "\n * Arch: " + arch + "\n * Type: " + type + - "\n\n**Describe the bug**\nA clear and concise description of what the bug is.\n\n**To Reproduce**\n" - "Steps to reproduce the behavior:\n1. Go to '...'\n2. Click on '....'\n3. Scroll down to '....'\n" - "4. See error\n\n**Expected behavior**\n" - "A clear and concise description of what you expected to happen.\n\n" - "**Screenshots**\nIf applicable, add screenshots to help explain your problem.\n\n" - "**Additional context**\nAdd any other context about the problem here."; + url = "https://github.com/rizinorg/cutter/issues/new?&body=**Environment information**\n* " + "Operating System: " + + osInfo + "\n* Cutter version: " + CUTTER_VERSION_FULL + "\n* File format: " + format + + "\n * Arch: " + arch + "\n * Type: " + type + + "\n\n**Describe the bug**\nA clear and concise description of what the bug " + "is.\n\n**To Reproduce**\n" + "Steps to reproduce the behavior:\n1. Go to '...'\n2. Click on '....'\n3. Scroll " + "down to '....'\n" + "4. See error\n\n**Expected behavior**\n" + "A clear and concise description of what you expected to happen.\n\n" + "**Screenshots**\nIf applicable, add screenshots to help explain your problem.\n\n" + "**Additional context**\nAdd any other context about the problem here."; - QDesktopServices::openUrl(QUrl(url, QUrl::TolerantMode)); + QDesktopServices::openUrl(QUrl(url, QUrl::TolerantMode)); } diff --git a/src/common/CachedFontMetrics.h b/src/common/CachedFontMetrics.h index f6b56f15..405c625d 100644 --- a/src/common/CachedFontMetrics.h +++ b/src/common/CachedFontMetrics.h @@ -11,8 +11,7 @@ template class CachedFontMetrics { public: - explicit CachedFontMetrics(const QFont &font) - : mFontMetrics(font) + explicit CachedFontMetrics(const QFont &font) : mFontMetrics(font) { memset(mWidths, 0, sizeof(mWidths)); mHeight = mFontMetrics.height(); @@ -20,7 +19,7 @@ public: T width(const QChar &ch) { - //return mFontMetrics.width(ch); + // return mFontMetrics.width(ch); auto unicode = ch.unicode(); if (unicode >= 0xD800) { if (unicode >= 0xE000) @@ -49,10 +48,7 @@ public: return result; } - T height() - { - return mHeight; - } + T height() { return mHeight; } T position(const QString &text, T offset) { @@ -84,7 +80,7 @@ private: T fetchWidth(QChar c) { -#if QT_VERSION < QT_VERSION_CHECK(5,11,0) +#if QT_VERSION < QT_VERSION_CHECK(5, 11, 0) return mFontMetrics.width(c); #else return mFontMetrics.horizontalAdvance(c); @@ -93,7 +89,7 @@ private: T fetchWidth(const QString &s) { -#if QT_VERSION < QT_VERSION_CHECK(5,11,0) +#if QT_VERSION < QT_VERSION_CHECK(5, 11, 0) return mFontMetrics.width(s); #else return mFontMetrics.horizontalAdvance(s); diff --git a/src/common/ColorThemeWorker.cpp b/src/common/ColorThemeWorker.cpp index 1f4fd61d..b842a148 100644 --- a/src/common/ColorThemeWorker.cpp +++ b/src/common/ColorThemeWorker.cpp @@ -10,80 +10,46 @@ #include "common/Configuration.h" const QStringList ColorThemeWorker::cutterSpecificOptions = { - "wordHighlight", - "lineHighlight", - "gui.main", - "gui.imports", - "highlightPC", - "gui.navbar.err", - "gui.navbar.seek", - "gui.navbar.pc", - "gui.navbar.sym", - "gui.dataoffset", - "gui.navbar.code", - "gui.navbar.empty", - "angui.navbar.str", - "gui.disass_selected", - "gui.breakpoint_background", - "gui.overview.node", - "gui.overview.fill", - "gui.overview.border", - "gui.border", - "gui.background", - "gui.alt_background", + "wordHighlight", "lineHighlight", "gui.main", + "gui.imports", "highlightPC", "gui.navbar.err", + "gui.navbar.seek", "gui.navbar.pc", "gui.navbar.sym", + "gui.dataoffset", "gui.navbar.code", "gui.navbar.empty", + "angui.navbar.str", "gui.disass_selected", "gui.breakpoint_background", + "gui.overview.node", "gui.overview.fill", "gui.overview.border", + "gui.border", "gui.background", "gui.alt_background", "gui.disass_selected" }; const QStringList ColorThemeWorker::rizinUnusedOptions = { - "linehl", - "wordhl", - "graph.box", - "graph.box2", - "graph.box3", - "graph.box4", - "graph.current", - "graph.box2", - "widget_sel", - "widget_bg", - "label", - "ai.write", - "invalid", - "ai.seq", - "args", - "ai.read", - "ai.exec", - "ai.ascii", - "prompt", - "graph.traced" + "linehl", "wordhl", "graph.box", "graph.box2", "graph.box3", + "graph.box4", "graph.current", "graph.box2", "widget_sel", "widget_bg", + "label", "ai.write", "invalid", "ai.seq", "args", + "ai.read", "ai.exec", "ai.ascii", "prompt", "graph.traced" }; -ColorThemeWorker::ColorThemeWorker(QObject *parent) : QObject (parent) +ColorThemeWorker::ColorThemeWorker(QObject *parent) : QObject(parent) { - char* szThemes = rz_str_home(RZ_HOME_THEMES); + char *szThemes = rz_str_home(RZ_HOME_THEMES); customRzThemesLocationPath = szThemes; rz_mem_free(szThemes); if (!QDir(customRzThemesLocationPath).exists()) { QDir().mkpath(customRzThemesLocationPath); } - QDir currDir { QStringLiteral("%1%2%3") - .arg(rz_sys_prefix(nullptr)) - .arg(RZ_SYS_DIR) - .arg(RZ_THEMES) + QDir currDir { + QStringLiteral("%1%2%3").arg(rz_sys_prefix(nullptr)).arg(RZ_SYS_DIR).arg(RZ_THEMES) }; if (currDir.exists()) { standardRzThemesLocationPath = currDir.absolutePath(); } else { - QMessageBox::critical(nullptr, - tr("Standard themes not found"), - tr("The Rizin standard themes could not be found in '%1'. " - "Most likely, Rizin is not properly installed.") - .arg(currDir.path()) - ); + QMessageBox::critical(nullptr, tr("Standard themes not found"), + tr("The Rizin standard themes could not be found in '%1'. " + "Most likely, Rizin is not properly installed.") + .arg(currDir.path())); } } -QColor ColorThemeWorker::mergeColors(const QColor& upper, const QColor& lower) const +QColor ColorThemeWorker::mergeColors(const QColor &upper, const QColor &lower) const { qreal r1, g1, b1, a1; qreal r2, g2, b2, a2; @@ -102,12 +68,10 @@ QColor ColorThemeWorker::mergeColors(const QColor& upper, const QColor& lower) c return res; } -QString ColorThemeWorker::copy(const QString &srcThemeName, - const QString ©ThemeName) const +QString ColorThemeWorker::copy(const QString &srcThemeName, const QString ©ThemeName) const { if (!isThemeExist(srcThemeName)) { - return tr("Theme %1 does not exist.") - .arg(srcThemeName); + return tr("Theme %1 does not exist.").arg(srcThemeName); } return save(getTheme(srcThemeName), copyThemeName); @@ -117,8 +81,7 @@ QString ColorThemeWorker::save(const QJsonDocument &theme, const QString &themeN { QFile fOut(QDir(customRzThemesLocationPath).filePath(themeName)); if (!fOut.open(QFile::WriteOnly | QFile::Truncate)) { - return tr("The file %1 cannot be opened.") - .arg(QFileInfo(fOut).filePath()); + return tr("The file %1 cannot be opened.").arg(QFileInfo(fOut).filePath()); } QJsonObject obj = theme.object(); @@ -137,12 +100,12 @@ QString ColorThemeWorker::save(const QJsonDocument &theme, const QString &themeN } if (cutterSpecificOptions.contains(it.key())) { fOut.write(QString("#~%1 rgb:%2\n") - .arg(it.key(), color.name(QColor::HexArgb).remove('#')) - .toUtf8()); + .arg(it.key(), color.name(QColor::HexArgb).remove('#')) + .toUtf8()); } else { fOut.write(QString("ec %1 rgb:%2\n") - .arg(it.key(), color.name(QColor::HexRgb).remove('#')) - .toUtf8()); + .arg(it.key(), color.name(QColor::HexRgb).remove('#')) + .toUtf8()); } } @@ -161,7 +124,7 @@ bool ColorThemeWorker::isThemeExist(const QString &name) const return themes.contains(name); } -QJsonDocument ColorThemeWorker::getTheme(const QString& themeName) const +QJsonDocument ColorThemeWorker::getTheme(const QString &themeName) const { int r, g, b, a; QVariantMap theme; @@ -178,7 +141,7 @@ QJsonDocument ColorThemeWorker::getTheme(const QString& themeName) const for (auto it = theme.begin(); it != theme.end(); it++) { auto arr = it.value().toList(); QColor(arr[0].toInt(), arr[1].toInt(), arr[2].toInt()).getRgb(&r, &g, &b, &a); - theme[it.key()] = QJsonArray({r, g, b, a}); + theme[it.key()] = QJsonArray({ r, g, b, a }); } ColorFlags colorFlags = ColorFlags::DarkFlag; @@ -186,9 +149,9 @@ QJsonDocument ColorThemeWorker::getTheme(const QString& themeName) const colorFlags = Configuration::relevantThemes[themeName]; } - for (auto& it : cutterSpecificOptions) { + for (auto &it : cutterSpecificOptions) { Configuration::cutterOptionColors[it][colorFlags].getRgb(&r, &g, &b, &a); - theme.insert(it, QJsonArray{r, g, b, a}); + theme.insert(it, QJsonArray { r, g, b, a }); } if (isCustomTheme(themeName)) { @@ -198,12 +161,14 @@ QJsonDocument ColorThemeWorker::getTheme(const QString& themeName) const } QStringList sl; for (auto &line : QString(src.readAll()).split('\n', CUTTER_QT_SKIP_EMPTY_PARTS)) { - sl = line.replace("#~", "ec ").replace("rgb:", "#").split(' ', CUTTER_QT_SKIP_EMPTY_PARTS); + sl = line.replace("#~", "ec ") + .replace("rgb:", "#") + .split(' ', CUTTER_QT_SKIP_EMPTY_PARTS); if (sl.size() != 3 || sl[0][0] == '#') { continue; } QColor(sl[2]).getRgb(&r, &g, &b, &a); - theme.insert(sl[1], QJsonArray({r, g, b, a})); + theme.insert(sl[1], QJsonArray({ r, g, b, a })); } } @@ -213,7 +178,8 @@ QJsonDocument ColorThemeWorker::getTheme(const QString& themeName) const // manualy converting instead of using QJsonObject::fromVariantMap because // Qt < 5.6 QJsonValue.fromVariant doesn't expect QVariant to already contain - // QJson values like QJsonArray. https://github.com/qt/qtbase/commit/26237f0a2d8db80024b601f676bbce54d483e672 + // QJson values like QJsonArray. + // https://github.com/qt/qtbase/commit/26237f0a2d8db80024b601f676bbce54d483e672 QJsonObject obj; for (auto it = theme.begin(); it != theme.end(); it++) { auto &value = it.value(); @@ -222,7 +188,6 @@ QJsonDocument ColorThemeWorker::getTheme(const QString& themeName) const } else { obj[it.key()] = QJsonValue::fromVariant(value); } - } return QJsonDocument(obj); @@ -239,26 +204,23 @@ QString ColorThemeWorker::deleteTheme(const QString &themeName) const QFile file(QDir(customRzThemesLocationPath).filePath(themeName)); if (file.isWritable()) { - return tr("You have no permission to write to %1") - .arg(QFileInfo(file).filePath()); + return tr("You have no permission to write to %1").arg(QFileInfo(file).filePath()); } if (!file.open(QFile::ReadOnly)) { - return tr("File %1 can not be opened.") - .arg(QFileInfo(file).filePath()); + return tr("File %1 can not be opened.").arg(QFileInfo(file).filePath()); } if (!file.remove()) { - return tr("File %1 can not be removed.") - .arg(QFileInfo(file).filePath()); + return tr("File %1 can not be removed.").arg(QFileInfo(file).filePath()); } return ""; } -QString ColorThemeWorker::importTheme(const QString& file) const +QString ColorThemeWorker::importTheme(const QString &file) const { QFileInfo src(file); - if (!src.exists()) { - return tr("File %1 does not exist.").arg(file); - } + if (!src.exists()) { + return tr("File %1 does not exist.").arg(file); + } bool ok; bool isTheme = isFileTheme(file, &ok); @@ -276,35 +238,36 @@ QString ColorThemeWorker::importTheme(const QString& file) const } if (QFile::copy(file, QDir(customRzThemesLocationPath).filePath(name))) { - return ""; - } else { - return tr("Error occurred during importing. " - "Please make sure you have an access to " - "the directory %1 and try again.") - .arg(src.dir().path()); + return ""; + } else { + return tr("Error occurred during importing. " + "Please make sure you have an access to " + "the directory %1 and try again.") + .arg(src.dir().path()); } } -QString ColorThemeWorker::renameTheme(const QString& themeName, const QString& newName) const +QString ColorThemeWorker::renameTheme(const QString &themeName, const QString &newName) const { if (isThemeExist(newName)) { - return tr("A color theme named \"%1\" already exists.").arg(newName); - } + return tr("A color theme named \"%1\" already exists.").arg(newName); + } - if (!isCustomTheme(themeName)) { - return tr("You can not rename standard Rizin themes."); - } + if (!isCustomTheme(themeName)) { + return tr("You can not rename standard Rizin themes."); + } - QDir dir = customRzThemesLocationPath; - bool ok = QFile::rename(dir.filePath(themeName), dir.filePath(newName)); - if (!ok) { - return tr("Something went wrong during renaming. " - "Please make sure you have access to the directory \"%1\".").arg(dir.path()); - } - return ""; + QDir dir = customRzThemesLocationPath; + bool ok = QFile::rename(dir.filePath(themeName), dir.filePath(newName)); + if (!ok) { + return tr("Something went wrong during renaming. " + "Please make sure you have access to the directory \"%1\".") + .arg(dir.path()); + } + return ""; } -bool ColorThemeWorker::isFileTheme(const QString& filePath, bool* ok) const +bool ColorThemeWorker::isFileTheme(const QString &filePath, bool *ok) const { QFile f(filePath); if (!f.open(QFile::ReadOnly)) { @@ -314,10 +277,12 @@ bool ColorThemeWorker::isFileTheme(const QString& filePath, bool* ok) const const QString colors = "black|red|white|green|magenta|yellow|cyan|blue|gray|none"; QString options = (Core()->cmdj("ecj").object().keys() << cutterSpecificOptions) - .join('|') - .replace(".", "\\."); + .join('|') + .replace(".", "\\."); - QString pattern = QString("((ec\\s+(%1)\\s+(((rgb:|#)[0-9a-fA-F]{3,8})|(%2))))\\s*").arg(options).arg(colors); + QString pattern = QString("((ec\\s+(%1)\\s+(((rgb:|#)[0-9a-fA-F]{3,8})|(%2))))\\s*") + .arg(options) + .arg(colors); // The below construct mimics the behaviour of QRegexP::exactMatch(), which was here before QRegularExpression regexp("\\A(?:" + pattern + ")\\z"); diff --git a/src/common/ColorThemeWorker.h b/src/common/ColorThemeWorker.h index 9eb6bb51..cc5f7d66 100644 --- a/src/common/ColorThemeWorker.h +++ b/src/common/ColorThemeWorker.h @@ -40,7 +40,6 @@ public: virtual ~ColorThemeWorker() {} - /** * @brief Copies @a srcThemeName with name @a copyThemeName. * @param srcThemeName @@ -59,10 +58,11 @@ public: * Name of theme to save. * @return "" on success or error message. */ - QString save(const QJsonDocument& theme, const QString &themeName) const; + QString save(const QJsonDocument &theme, const QString &themeName) const; /** - * @brief Returns whether or not @a themeName theme is custom (created by user or imported) or not. + * @brief Returns whether or not @a themeName theme is custom (created by user or imported) or + * not. * @param themeName * Name of theme to check. */ @@ -75,7 +75,8 @@ public: bool isThemeExist(const QString &name) const; /** - * @brief Returns theme as Json where key is option name and value is array of 3 Ints (Red, Green, Blue). + * @brief Returns theme as Json where key is option name and value is array of 3 Ints (Red, + * Green, Blue). * @param themeName * Theme to get. */ @@ -93,13 +94,13 @@ public: * @brief Imports theme from @a file. * @return "" on success or error message. */ - QString importTheme(const QString& file) const; + QString importTheme(const QString &file) const; /** * @brief Renames theme from @a themeName to @a newName. * @return "" on success or error message. */ - QString renameTheme(const QString& themeName, const QString& newName) const; + QString renameTheme(const QString &themeName, const QString &newName) const; /** * @brief Returns whether or not file at @a filePath is a color theme. diff --git a/src/common/Colors.cpp b/src/common/Colors.cpp index da11b986..372172e7 100644 --- a/src/common/Colors.cpp +++ b/src/common/Colors.cpp @@ -1,11 +1,7 @@ #include "Colors.h" #include "common/Configuration.h" -Colors::Colors() -{ - -} - +Colors::Colors() {} void Colors::colorizeAssembly(RichTextPainter::List &list, QString opcode, ut64 type_num) { @@ -101,4 +97,3 @@ QString Colors::getColor(ut64 type) return "invalid"; } } - diff --git a/src/common/CommandTask.cpp b/src/common/CommandTask.cpp index 7add426e..c027cab1 100644 --- a/src/common/CommandTask.cpp +++ b/src/common/CommandTask.cpp @@ -7,7 +7,8 @@ CommandTask::CommandTask(const QString &cmd, ColorMode colorMode, bool outFormat { } -void CommandTask::runTask() { +void CommandTask::runTask() +{ TempConfig tempConfig; tempConfig.set("scr.color", colorMode); auto res = Core()->cmdTask(cmd); diff --git a/src/common/CommandTask.h b/src/common/CommandTask.h index e0448af4..24a74a5b 100644 --- a/src/common/CommandTask.h +++ b/src/common/CommandTask.h @@ -5,16 +5,22 @@ #include "common/AsyncTask.h" #include "core/Cutter.h" -class CUTTER_EXPORT CommandTask : public AsyncTask +class CUTTER_EXPORT CommandTask : public AsyncTask { -Q_OBJECT + Q_OBJECT public: - enum ColorMode {DISABLED=COLOR_MODE_DISABLED, MODE_16=COLOR_MODE_16, MODE_256=COLOR_MODE_256, MODE_16M=COLOR_MODE_16M}; + enum ColorMode { + DISABLED = COLOR_MODE_DISABLED, + MODE_16 = COLOR_MODE_16, + MODE_256 = COLOR_MODE_256, + MODE_16M = COLOR_MODE_16M + }; - CommandTask(const QString &cmd, ColorMode colorMode=ColorMode::DISABLED, bool outFormatHtml=false); + CommandTask(const QString &cmd, ColorMode colorMode = ColorMode::DISABLED, + bool outFormatHtml = false); - QString getTitle() override { return tr("Running Command"); } + QString getTitle() override { return tr("Running Command"); } signals: void finished(const QString &result); @@ -28,4 +34,4 @@ private: bool outFormatHtml; }; -#endif //COMMANDTASK_H +#endif // COMMANDTASK_H diff --git a/src/common/Configuration.cpp b/src/common/Configuration.cpp index e36050ee..c92ddffd 100644 --- a/src/common/Configuration.cpp +++ b/src/common/Configuration.cpp @@ -7,9 +7,9 @@ #include #ifdef CUTTER_ENABLE_KSYNTAXHIGHLIGHTING -#include -#include -#include +# include +# include +# include #endif #include "common/ColorThemeWorker.h" @@ -21,75 +21,71 @@ * and for light - only light ones. */ const QHash Configuration::relevantThemes = { - { "ayu", DarkFlag }, - { "consonance", DarkFlag }, - { "darkda", DarkFlag }, - { "onedark", DarkFlag }, - { "solarized", DarkFlag }, - { "zenburn", DarkFlag }, - { "cutter", LightFlag }, - { "dark", LightFlag }, - { "matrix", LightFlag }, - { "tango", LightFlag }, - { "white", LightFlag } + { "ayu", DarkFlag }, { "consonance", DarkFlag }, { "darkda", DarkFlag }, + { "onedark", DarkFlag }, { "solarized", DarkFlag }, { "zenburn", DarkFlag }, + { "cutter", LightFlag }, { "dark", LightFlag }, { "matrix", LightFlag }, + { "tango", LightFlag }, { "white", LightFlag } }; static const QString DEFAULT_LIGHT_COLOR_THEME = "cutter"; static const QString DEFAULT_DARK_COLOR_THEME = "ayu"; - const QHash> Configuration::cutterOptionColors = { - { "gui.cflow", { { DarkFlag, QColor(0xff, 0xff, 0xff) }, - { LightFlag, QColor(0x00, 0x00, 0x00) }} }, - { "gui.dataoffset", { { DarkFlag, QColor(0xff, 0xff, 0xff) }, - { LightFlag, QColor(0x00, 0x00, 0x00) }} }, - { "gui.imports", { { DarkFlag, QColor(0x32, 0x8c, 0xff) }, - { LightFlag, QColor(0x32, 0x8c, 0xff) }} }, - { "gui.item_invalid", { { DarkFlag, QColor(0x9b, 0x9b, 0x9b) }, - { LightFlag, QColor(0x9b, 0x9b, 0x9b) }} }, - { "gui.main", { { DarkFlag, QColor(0x00, 0x80, 0x00) }, - { LightFlag, QColor(0x00, 0x80, 0x00) }} }, - { "gui.item_unsafe", { { DarkFlag, QColor(0xff, 0x81, 0x7b) }, - { LightFlag, QColor(0xff, 0x81, 0x7b) }} }, - { "gui.navbar.seek", { { DarkFlag, QColor(0xe9, 0x56, 0x56) }, - { LightFlag, QColor(0xff, 0x00, 0x00) }} }, - { "gui.navbar.pc", { { DarkFlag, QColor(0x42, 0xee, 0xf4) }, - { LightFlag, QColor(0x42, 0xee, 0xf4) }} }, - { "gui.navbar.code", { { DarkFlag, QColor(0x82, 0xc8, 0x6f) }, - { LightFlag, QColor(0x68, 0xe5, 0x45) }} }, - { "gui.navbar.str", { { DarkFlag, QColor(0x6f, 0x86, 0xd8) }, - { LightFlag, QColor(0x45, 0x68, 0xe5) }} }, - { "gui.navbar.sym", { { DarkFlag, QColor(0xdd, 0xa3, 0x68) }, - { LightFlag, QColor(0xe5, 0x96, 0x45) }} }, - { "gui.navbar.empty", { { DarkFlag, QColor(0x64, 0x64, 0x64) }, - { LightFlag, QColor(0xdc, 0xec, 0xf5) }} }, - { "gui.breakpoint_background", { { DarkFlag, QColor(0x8c, 0x4c, 0x4c) }, - { LightFlag, QColor(0xe9, 0x8f, 0x8f) }} }, - { "gui.overview.node", { { DarkFlag, QColor(0x64, 0x64, 0x64) }, - { LightFlag, QColor(0xf5, 0xfa, 0xff) }} }, - { "gui.tooltip.background", { { DarkFlag, QColor(0x2a, 0x2c, 0x2e) }, - { LightFlag, QColor(0xfa, 0xfc, 0xfe) }} }, - { "gui.tooltip.foreground", { { DarkFlag, QColor(0xfa, 0xfc, 0xfe) }, - { LightFlag, QColor(0x2a, 0x2c, 0x2e) }} }, - { "gui.border", { { DarkFlag, QColor(0x64, 0x64, 0x64) }, - { LightFlag, QColor(0x91, 0xc8, 0xfa) }} }, - { "gui.background", { { DarkFlag, QColor(0x25, 0x28, 0x2b) }, - { LightFlag, QColor(0xff, 0xff, 0xff) }} }, - { "gui.alt_background", { { DarkFlag, QColor(0x1c, 0x1f, 0x24) }, - { LightFlag, QColor(0xf5, 0xfa, 0xff) }} }, - { "gui.disass_selected", { { DarkFlag, QColor(0x1f, 0x22, 0x28) }, - { LightFlag, QColor(0xff, 0xff, 0xff) }} }, - { "lineHighlight", { { DarkFlag, QColor(0x15, 0x1d, 0x1d, 0x96) }, - { LightFlag, QColor(0xd2, 0xd2, 0xff, 0x96) }} }, - { "wordHighlight", { { DarkFlag, QColor(0x34, 0x3a, 0x47, 0xff) }, - { LightFlag, QColor(0xb3, 0x77, 0xd6, 0x3c) }} }, - { "highlightPC", { { DarkFlag, QColor(0x57, 0x1a, 0x07) }, - { LightFlag, QColor(0xd6, 0xff, 0xd2) }} }, - { "gui.overview.fill", { { DarkFlag, QColor(0xff, 0xff, 0xff, 0x28) }, - { LightFlag, QColor(0xaf, 0xd9, 0xea, 0x41) }} }, - { "gui.overview.border", { { DarkFlag, QColor(0x63, 0xda, 0xe8, 0x32) }, - { LightFlag, QColor(0x63, 0xda, 0xe8, 0x32) }} }, - { "gui.navbar.err", { { DarkFlag, QColor(0x03, 0xaa, 0xf5) }, - { LightFlag, QColor(0x03, 0xaa, 0xf5) }} } + { "gui.cflow", + { { DarkFlag, QColor(0xff, 0xff, 0xff) }, { LightFlag, QColor(0x00, 0x00, 0x00) } } }, + { "gui.dataoffset", + { { DarkFlag, QColor(0xff, 0xff, 0xff) }, { LightFlag, QColor(0x00, 0x00, 0x00) } } }, + { "gui.imports", + { { DarkFlag, QColor(0x32, 0x8c, 0xff) }, { LightFlag, QColor(0x32, 0x8c, 0xff) } } }, + { "gui.item_invalid", + { { DarkFlag, QColor(0x9b, 0x9b, 0x9b) }, { LightFlag, QColor(0x9b, 0x9b, 0x9b) } } }, + { "gui.main", + { { DarkFlag, QColor(0x00, 0x80, 0x00) }, { LightFlag, QColor(0x00, 0x80, 0x00) } } }, + { "gui.item_unsafe", + { { DarkFlag, QColor(0xff, 0x81, 0x7b) }, { LightFlag, QColor(0xff, 0x81, 0x7b) } } }, + { "gui.navbar.seek", + { { DarkFlag, QColor(0xe9, 0x56, 0x56) }, { LightFlag, QColor(0xff, 0x00, 0x00) } } }, + { "gui.navbar.pc", + { { DarkFlag, QColor(0x42, 0xee, 0xf4) }, { LightFlag, QColor(0x42, 0xee, 0xf4) } } }, + { "gui.navbar.code", + { { DarkFlag, QColor(0x82, 0xc8, 0x6f) }, { LightFlag, QColor(0x68, 0xe5, 0x45) } } }, + { "gui.navbar.str", + { { DarkFlag, QColor(0x6f, 0x86, 0xd8) }, { LightFlag, QColor(0x45, 0x68, 0xe5) } } }, + { "gui.navbar.sym", + { { DarkFlag, QColor(0xdd, 0xa3, 0x68) }, { LightFlag, QColor(0xe5, 0x96, 0x45) } } }, + { "gui.navbar.empty", + { { DarkFlag, QColor(0x64, 0x64, 0x64) }, { LightFlag, QColor(0xdc, 0xec, 0xf5) } } }, + { "gui.breakpoint_background", + { { DarkFlag, QColor(0x8c, 0x4c, 0x4c) }, { LightFlag, QColor(0xe9, 0x8f, 0x8f) } } }, + { "gui.overview.node", + { { DarkFlag, QColor(0x64, 0x64, 0x64) }, { LightFlag, QColor(0xf5, 0xfa, 0xff) } } }, + { "gui.tooltip.background", + { { DarkFlag, QColor(0x2a, 0x2c, 0x2e) }, { LightFlag, QColor(0xfa, 0xfc, 0xfe) } } }, + { "gui.tooltip.foreground", + { { DarkFlag, QColor(0xfa, 0xfc, 0xfe) }, { LightFlag, QColor(0x2a, 0x2c, 0x2e) } } }, + { "gui.border", + { { DarkFlag, QColor(0x64, 0x64, 0x64) }, { LightFlag, QColor(0x91, 0xc8, 0xfa) } } }, + { "gui.background", + { { DarkFlag, QColor(0x25, 0x28, 0x2b) }, { LightFlag, QColor(0xff, 0xff, 0xff) } } }, + { "gui.alt_background", + { { DarkFlag, QColor(0x1c, 0x1f, 0x24) }, { LightFlag, QColor(0xf5, 0xfa, 0xff) } } }, + { "gui.disass_selected", + { { DarkFlag, QColor(0x1f, 0x22, 0x28) }, { LightFlag, QColor(0xff, 0xff, 0xff) } } }, + { "lineHighlight", + { { DarkFlag, QColor(0x15, 0x1d, 0x1d, 0x96) }, + { LightFlag, QColor(0xd2, 0xd2, 0xff, 0x96) } } }, + { "wordHighlight", + { { DarkFlag, QColor(0x34, 0x3a, 0x47, 0xff) }, + { LightFlag, QColor(0xb3, 0x77, 0xd6, 0x3c) } } }, + { "highlightPC", + { { DarkFlag, QColor(0x57, 0x1a, 0x07) }, { LightFlag, QColor(0xd6, 0xff, 0xd2) } } }, + { "gui.overview.fill", + { { DarkFlag, QColor(0xff, 0xff, 0xff, 0x28) }, + { LightFlag, QColor(0xaf, 0xd9, 0xea, 0x41) } } }, + { "gui.overview.border", + { { DarkFlag, QColor(0x63, 0xda, 0xe8, 0x32) }, + { LightFlag, QColor(0x63, 0xda, 0xe8, 0x32) } } }, + { "gui.navbar.err", + { { DarkFlag, QColor(0x03, 0xaa, 0xf5) }, { LightFlag, QColor(0x03, 0xaa, 0xf5) } } } }; Configuration *Configuration::mPtr = nullptr; @@ -97,54 +93,50 @@ Configuration *Configuration::mPtr = nullptr; /** * @brief All asm.* options saved as settings. Values are the default values. */ -static const QHash asmOptions = { - { "asm.esil", false }, - { "asm.pseudo", false }, - { "asm.offset", true }, - { "asm.xrefs", false }, - { "asm.indent", false }, - { "asm.describe", false }, - { "asm.slow", true }, - { "asm.lines", true }, - { "asm.lines.fcn", true }, - { "asm.flags.offset", false }, - { "asm.emu", false }, - { "emu.str", false}, - { "asm.cmt.right", true }, - { "asm.cmt.col", 35 }, - { "asm.var.summary", false }, - { "asm.bytes", false }, - { "asm.size", false }, - { "asm.bytes.space", false }, - { "asm.lbytes", true }, - { "asm.nbytes", 10 }, - { "asm.syntax", "intel" }, - { "asm.ucase", false }, - { "asm.bb.line", false }, - { "asm.capitalize", false }, - { "asm.sub.var", true }, - { "asm.sub.varonly", true }, - { "asm.tabs", 8 }, - { "asm.tabs.off", 5 }, - { "asm.marks", false }, - { "asm.refptr", false }, - { "asm.flags.real", true }, - { "asm.reloff", false }, - { "asm.reloff.flags", false }, - { "esil.breakoninvalid",true }, - { "graph.offset", false} -}; - +static const QHash asmOptions = { { "asm.esil", false }, + { "asm.pseudo", false }, + { "asm.offset", true }, + { "asm.xrefs", false }, + { "asm.indent", false }, + { "asm.describe", false }, + { "asm.slow", true }, + { "asm.lines", true }, + { "asm.lines.fcn", true }, + { "asm.flags.offset", false }, + { "asm.emu", false }, + { "emu.str", false }, + { "asm.cmt.right", true }, + { "asm.cmt.col", 35 }, + { "asm.var.summary", false }, + { "asm.bytes", false }, + { "asm.size", false }, + { "asm.bytes.space", false }, + { "asm.lbytes", true }, + { "asm.nbytes", 10 }, + { "asm.syntax", "intel" }, + { "asm.ucase", false }, + { "asm.bb.line", false }, + { "asm.capitalize", false }, + { "asm.sub.var", true }, + { "asm.sub.varonly", true }, + { "asm.tabs", 8 }, + { "asm.tabs.off", 5 }, + { "asm.marks", false }, + { "asm.refptr", false }, + { "asm.flags.real", true }, + { "asm.reloff", false }, + { "asm.reloff.flags", false }, + { "esil.breakoninvalid", true }, + { "graph.offset", false } }; Configuration::Configuration() : QObject(), nativePalette(qApp->palette()) { mPtr = this; if (!s.isWritable()) { - QMessageBox::critical(nullptr, - tr("Critical!"), - tr("!!! Settings are not writable! Make sure you have a write access to \"%1\"") - .arg(s.fileName()) - ); + QMessageBox::critical( + nullptr, tr("Critical!"), + tr("!!! Settings are not writable! Make sure you have a write access to \"%1\"") + .arg(s.fileName())); } #ifdef CUTTER_ENABLE_KSYNTAXHIGHLIGHTING kSyntaxHighlightingRepository = nullptr; @@ -200,7 +192,7 @@ void Configuration::resetAll() { // Don't reset all rizin vars, that currently breaks a bunch of stuff. // settingsFile.remove()+loadInitials() should reset all settings configurable using Cutter GUI. - //Core()->cmdRaw("e-"); + // Core()->cmdRaw("e-"); Core()->setSettings(); // Delete the file so no extra configuration is in it. @@ -247,8 +239,8 @@ void Configuration::setLocale(const QLocale &l) */ bool Configuration::setLocaleByName(const QString &language) { - const auto &allLocales = QLocale::matchingLocales(QLocale::AnyLanguage, QLocale::AnyScript, - QLocale::AnyCountry); + const auto &allLocales = + QLocale::matchingLocales(QLocale::AnyLanguage, QLocale::AnyScript, QLocale::AnyCountry); for (auto &it : allLocales) { if (QString::compare(it.nativeLanguageName(), language, Qt::CaseInsensitive) == 0) { @@ -375,9 +367,9 @@ const QFont Configuration::getBaseFont() const const QFont Configuration::getFont() const { - QFont font = getBaseFont(); - font.setPointSizeF(font.pointSizeF() * getZoomFactor()); - return font; + QFont font = getBaseFont(); + font.setPointSizeF(font.pointSizeF() * getZoomFactor()); + return font; } void Configuration::setFont(const QFont &font) @@ -391,26 +383,26 @@ void Configuration::refreshFont() emit fontsUpdated(); } -qreal Configuration::getZoomFactor() const { - qreal fontZoom = s.value("zoomFactor", 1.0).value(); - return qMax(fontZoom, 0.1); +qreal Configuration::getZoomFactor() const +{ + qreal fontZoom = s.value("zoomFactor", 1.0).value(); + return qMax(fontZoom, 0.1); } -void Configuration::setZoomFactor(qreal zoom) { - s.setValue("zoomFactor", qMax(zoom, 0.1)); - emit fontsUpdated(); +void Configuration::setZoomFactor(qreal zoom) +{ + s.setValue("zoomFactor", qMax(zoom, 0.1)); + emit fontsUpdated(); } QString Configuration::getLastThemeOf(const CutterInterfaceTheme &currInterfaceTheme) const { - return s.value("lastThemeOf." + currInterfaceTheme.name, - Config()->getColorTheme()).toString(); + return s.value("lastThemeOf." + currInterfaceTheme.name, Config()->getColorTheme()).toString(); } void Configuration::setInterfaceTheme(int theme) { - if (theme >= cutterInterfaceThemesList().size() || - theme < 0) { + if (theme >= cutterInterfaceThemesList().size() || theme < 0) { theme = 0; } s.setValue("ColorPalette", theme); @@ -464,10 +456,9 @@ KSyntaxHighlighting::Theme Configuration::getKSyntaxHighlightingTheme() if (!repo) { return KSyntaxHighlighting::Theme(); } - return repo->defaultTheme( - getCurrentTheme()->flag & DarkFlag - ? KSyntaxHighlighting::Repository::DefaultTheme::DarkTheme - : KSyntaxHighlighting::Repository::DefaultTheme::LightTheme); + return repo->defaultTheme(getCurrentTheme()->flag & DarkFlag + ? KSyntaxHighlighting::Repository::DefaultTheme::DarkTheme + : KSyntaxHighlighting::Repository::DefaultTheme::LightTheme); } #endif @@ -487,9 +478,8 @@ QSyntaxHighlighter *Configuration::createSyntaxHighlighter(QTextDocument *docume QString Configuration::getLogoFile() { - return windowColorIsDark() - ? QString(":/img/cutter_white_plain.svg") - : QString(":/img/cutter_plain.svg"); + return windowColorIsDark() ? QString(":/img/cutter_white_plain.svg") + : QString(":/img/cutter_plain.svg"); } /** @@ -502,7 +492,8 @@ void Configuration::setColor(const QString &name, const QColor &color) s.setValue("colors." + name, color); } -void Configuration::setLastThemeOf(const CutterInterfaceTheme &currInterfaceTheme, const QString &theme) +void Configuration::setLastThemeOf(const CutterInterfaceTheme &currInterfaceTheme, + const QString &theme) { s.setValue("lastThemeOf." + currInterfaceTheme.name, theme); } @@ -572,13 +563,13 @@ void Configuration::applySavedAsmOptions() } } -const QList& Configuration::cutterInterfaceThemesList() +const QList &Configuration::cutterInterfaceThemesList() { static const QList list = { { "Native", Configuration::nativeWindowIsDark() ? DarkFlag : LightFlag }, - { "Dark", DarkFlag }, + { "Dark", DarkFlag }, { "Midnight", DarkFlag }, - { "Light", LightFlag } + { "Light", LightFlag } }; return list; } @@ -599,7 +590,6 @@ QVariant Configuration::getConfigVar(const QString &key) return QVariant(); } - bool Configuration::getConfigBool(const QString &key) { return getConfigVar(key).toBool(); @@ -644,8 +634,8 @@ QStringList Configuration::getAvailableTranslations() if (!dir.exists()) { continue; } - const QStringList &currTrFileNames = dir.entryList(QStringList("cutter_*.qm"), QDir::Files, - QDir::Name); + const QStringList &currTrFileNames = + dir.entryList(QStringList("cutter_*.qm"), QDir::Files, QDir::Name); for (const auto &trFile : currTrFileNames) { fileNamesSet << trFile; } @@ -655,16 +645,16 @@ QStringList Configuration::getAvailableTranslations() std::sort(fileNames.begin(), fileNames.end()); QStringList languages; QString currLanguageName; - auto allLocales = QLocale::matchingLocales(QLocale::AnyLanguage, QLocale::AnyScript, - QLocale::AnyCountry); + auto allLocales = + QLocale::matchingLocales(QLocale::AnyLanguage, QLocale::AnyScript, QLocale::AnyCountry); for (auto i : fileNames) { QString localeName = i.mid(sizeof("cutter_") - 1, 2); for (auto j : allLocales) { if (j.name().startsWith(localeName)) { currLanguageName = j.nativeLanguageName(); - currLanguageName = currLanguageName.at(0).toUpper() + - currLanguageName.right(currLanguageName.length() - 1); + currLanguageName = currLanguageName.at(0).toUpper() + + currLanguageName.right(currLanguageName.length() - 1); languages << currLanguageName; break; } diff --git a/src/common/Configuration.h b/src/common/Configuration.h index 513533a3..f20cbe26 100644 --- a/src/common/Configuration.h +++ b/src/common/Configuration.h @@ -10,26 +10,25 @@ #ifdef CUTTER_ENABLE_KSYNTAXHIGHLIGHTING namespace KSyntaxHighlighting { - class Repository; - class Theme; +class Repository; +class Theme; } #endif class QSyntaxHighlighter; class QTextDocument; - enum ColorFlags { LightFlag = 1, DarkFlag = 2, }; -struct CutterInterfaceTheme { +struct CutterInterfaceTheme +{ QString name; ColorFlags flag; }; - class CUTTER_EXPORT Configuration : public QObject { Q_OBJECT @@ -56,7 +55,7 @@ private: void applySavedAsmOptions(); public: - static const QList& cutterInterfaceThemesList(); + static const QList &cutterInterfaceThemesList(); static const QHash relevantThemes; static const QHash> cutterOptionColors; @@ -83,7 +82,7 @@ public: * @brief Gets the configured font set by the font selection box * @return the configured font */ - const QFont getBaseFont() const; + const QFont getBaseFont() const; /** * @brief Gets the configured font with the point size adjusted by the configured zoom @@ -101,10 +100,7 @@ public: void setLastThemeOf(const CutterInterfaceTheme &currInterfaceTheme, const QString &theme); QString getLastThemeOf(const CutterInterfaceTheme &currInterfaceTheme) const; void setInterfaceTheme(int theme); - int getInterfaceTheme() - { - return s.value("ColorPalette", 0).toInt(); - } + int getInterfaceTheme() { return s.value("ColorPalette", 0).toInt(); } const CutterInterfaceTheme *getCurrentTheme(); @@ -126,7 +122,7 @@ public: // Asm Options void resetToDefaultAsmOptions(); - QString getColorTheme() const { return s.value("theme", "cutter").toString(); } + QString getColorTheme() const { return s.value("theme", "cutter").toString(); } void setColorTheme(const QString &theme); /** * @brief Change current color theme if it doesn't much native theme's darkness. @@ -164,27 +160,16 @@ public: bool isDecompilerAnnotationHighlighterEnabled(); // Graph - int getGraphBlockMaxChars() const - { - return s.value("graph.maxcols", 100).toInt(); - } - void setGraphBlockMaxChars(int ch) - { - s.setValue("graph.maxcols", ch); - } + int getGraphBlockMaxChars() const { return s.value("graph.maxcols", 100).toInt(); } + void setGraphBlockMaxChars(int ch) { s.setValue("graph.maxcols", ch); } - int getGraphMinFontSize() const - { - return s.value("graph.minfontsize", 4).toInt(); - } + int getGraphMinFontSize() const { return s.value("graph.minfontsize", 4).toInt(); } - void setGraphMinFontSize(int sz) - { - s.setValue("graph.minfontsize", sz); - } + void setGraphMinFontSize(int sz) { s.setValue("graph.minfontsize", sz); } /** - * @brief Getters and setters for the transaparent option state and scale factor for bitmap graph exports. + * @brief Getters and setters for the transaparent option state and scale factor for bitmap + * graph exports. */ bool getBitmapTransparentState(); double getBitmapExportScaleFactor(); @@ -202,7 +187,8 @@ public: /** * @brief Enable or disable the displaying of the entry offset in each graph block - * @param enabled set this to true for displaying the entry offset in each graph block, false otherwise + * @param enabled set this to true for displaying the entry offset in each graph block, false + * otherwise */ void setGraphBlockEntryOffset(bool enabled); diff --git a/src/common/CrashHandler.cpp b/src/common/CrashHandler.cpp index 7e7731d2..4c6e56b8 100644 --- a/src/common/CrashHandler.cpp +++ b/src/common/CrashHandler.cpp @@ -14,12 +14,12 @@ #include #include -#if defined (Q_OS_LINUX) -#include "client/linux/handler/exception_handler.h" -#elif defined (Q_OS_WIN32) -#include "client/windows/handler/exception_handler.h" -#elif defined (Q_OS_MACOS) -#include "client/mac/handler/exception_handler.h" +#if defined(Q_OS_LINUX) +# include "client/linux/handler/exception_handler.h" +#elif defined(Q_OS_WIN32) +# include "client/windows/handler/exception_handler.h" +#elif defined(Q_OS_MACOS) +# include "client/mac/handler/exception_handler.h" #endif // Q_OS static google_breakpad::ExceptionHandler *exceptionHandler = nullptr; @@ -32,30 +32,27 @@ static void finishCrashHandler() #ifdef Q_OS_WIN32 // Called if crash dump was successfully created // Saves path to file -bool callback(const wchar_t *_dump_dir, - const wchar_t *_minidump_id, - void *context, EXCEPTION_POINTERS *exinfo, - MDRawAssertionInfo *assertion, - bool success) +bool callback(const wchar_t *_dump_dir, const wchar_t *_minidump_id, void *context, + EXCEPTION_POINTERS *exinfo, MDRawAssertionInfo *assertion, bool success) { const QDir dir = QString::fromWCharArray(_dump_dir); const QString id = QString::fromWCharArray(_minidump_id); QProcess::startDetached(QCoreApplication::applicationFilePath(), - { "--start-crash-handler", dir.filePath(id + ".dmp") }); + { "--start-crash-handler", dir.filePath(id + ".dmp") }); _exit(1); return true; } -#elif defined (Q_OS_LINUX) +#elif defined(Q_OS_LINUX) // Called if crash dump was successfully created // Saves path to file bool callback(const google_breakpad::MinidumpDescriptor &md, void *context, bool b) { QProcess::startDetached(QCoreApplication::applicationFilePath(), - { "--start-crash-handler", md.path() }); + { "--start-crash-handler", md.path() }); _exit(1); return true; } -#elif defined (Q_OS_MACOS) +#elif defined(Q_OS_MACOS) // Called if crash dump was successfully created // Saves path to file bool callback(const char *dump_dir, const char *minidump_id, void *context, bool succeeded) @@ -63,7 +60,7 @@ bool callback(const char *dump_dir, const char *minidump_id, void *context, bool const QDir dir = QString::fromUtf8(dump_dir); const QString id = QString::fromUtf8(minidump_id); QProcess::startDetached(QCoreApplication::applicationFilePath(), - { "--start-crash-handler", dir.filePath(id + ".dmp") }); + { "--start-crash-handler", dir.filePath(id + ".dmp") }); _exit(1); return true; } @@ -77,29 +74,22 @@ void initCrashHandler() // Here will be placed crash dump at the first place // and then moved if needed -#if defined (Q_OS_LINUX) - static std::string tmpLocation = QStandardPaths::writableLocation(QStandardPaths::TempLocation).toStdString(); - exceptionHandler = new google_breakpad::ExceptionHandler(google_breakpad::MinidumpDescriptor(tmpLocation), - nullptr, - callback, - nullptr, - true, - -1); -#elif defined (Q_OS_MACOS) - static std::string tmpLocation = QStandardPaths::writableLocation(QStandardPaths::TempLocation).toStdString(); - exceptionHandler = new google_breakpad::ExceptionHandler(tmpLocation, - nullptr, - callback, - nullptr, - true, - nullptr); +#if defined(Q_OS_LINUX) + static std::string tmpLocation = + QStandardPaths::writableLocation(QStandardPaths::TempLocation).toStdString(); + exceptionHandler = new google_breakpad::ExceptionHandler( + google_breakpad::MinidumpDescriptor(tmpLocation), nullptr, callback, nullptr, true, -1); +#elif defined(Q_OS_MACOS) + static std::string tmpLocation = + QStandardPaths::writableLocation(QStandardPaths::TempLocation).toStdString(); + exceptionHandler = new google_breakpad::ExceptionHandler(tmpLocation, nullptr, callback, + nullptr, true, nullptr); #else - static std::wstring tmpLocation = QStandardPaths::writableLocation(QStandardPaths::TempLocation).toStdWString(); - exceptionHandler = new google_breakpad::ExceptionHandler(tmpLocation, - nullptr, - callback, - nullptr, - google_breakpad::ExceptionHandler::HANDLER_ALL); + static std::wstring tmpLocation = + QStandardPaths::writableLocation(QStandardPaths::TempLocation).toStdWString(); + exceptionHandler = + new google_breakpad::ExceptionHandler(tmpLocation, nullptr, callback, nullptr, + google_breakpad::ExceptionHandler::HANDLER_ALL); #endif atexit(finishCrashHandler); } @@ -125,14 +115,13 @@ void showCrashDialog(const QString &dumpFile) if (placementFailCounter == 4) { break; } - dumpSaveFileName = QFileDialog::getSaveFileName(nullptr, - QObject::tr("Choose a directory to save the crash dump in"), - QStandardPaths::writableLocation(QStandardPaths::HomeLocation) + - QDir::separator() + - "Cutter_crash_dump_" - + QDate::currentDate().toString("dd.MM.yy") + "_" - + QTime::currentTime().toString("HH.mm.ss") + ".dmp", - QObject::tr("Minidump (*.dmp)")); + dumpSaveFileName = QFileDialog::getSaveFileName( + nullptr, QObject::tr("Choose a directory to save the crash dump in"), + QStandardPaths::writableLocation(QStandardPaths::HomeLocation) + + QDir::separator() + "Cutter_crash_dump_" + + QDate::currentDate().toString("dd.MM.yy") + "_" + + QTime::currentTime().toString("HH.mm.ss") + ".dmp", + QObject::tr("Minidump (*.dmp)")); if (dumpSaveFileName.isEmpty()) { return; @@ -141,18 +130,18 @@ void showCrashDialog(const QString &dumpFile) ok = true; break; } - QMessageBox::critical(nullptr, - QObject::tr("Save Crash Dump"), + QMessageBox::critical(nullptr, QObject::tr("Save Crash Dump"), QObject::tr("Failed to write to %1.
" "Please make sure you have access to that directory " - "and try again.").arg(QFileInfo(dumpSaveFileName).dir().path())); + "and try again.") + .arg(QFileInfo(dumpSaveFileName).dir().path())); } while (true); if (ok) { QMessageBox info; info.setWindowTitle(QObject::tr("Success")); info.setText(QObject::tr("Crash dump was successfully created.") - .arg(QFileInfo(dumpSaveFileName).dir().path())); + .arg(QFileInfo(dumpSaveFileName).dir().path())); info.setStandardButtons(QMessageBox::Yes | QMessageBox::No); info.button(QMessageBox::Yes)->setText(QObject::tr("Open an Issue")); @@ -164,8 +153,7 @@ void showCrashDialog(const QString &dumpFile) openIssue(); } } else { - QMessageBox::critical(nullptr, - QObject::tr("Error"), + QMessageBox::critical(nullptr, QObject::tr("Error"), QObject::tr("Error occurred during crash dump creation.")); } } else { diff --git a/src/common/CrashHandler.h b/src/common/CrashHandler.h index be961be7..77ef6bf2 100644 --- a/src/common/CrashHandler.h +++ b/src/common/CrashHandler.h @@ -8,7 +8,7 @@ * * If CUTTER_ENABLE_CRASH_REPORTS is true, initializes * crash handling and reporting, otherwise does nothing. -*/ + */ void initCrashHandler(); void showCrashDialog(const QString &dumpFile); diff --git a/src/common/CutterLayout.h b/src/common/CutterLayout.h index b817bf80..2870c007 100644 --- a/src/common/CutterLayout.h +++ b/src/common/CutterLayout.h @@ -6,8 +6,7 @@ #include #include -namespace Cutter -{ +namespace Cutter { struct CutterLayout { diff --git a/src/common/CutterSeekable.cpp b/src/common/CutterSeekable.cpp index 4a0648a7..f8b0805a 100644 --- a/src/common/CutterSeekable.cpp +++ b/src/common/CutterSeekable.cpp @@ -3,10 +3,7 @@ #include - -CutterSeekable::CutterSeekable(QObject *parent) - : - QObject(parent) +CutterSeekable::CutterSeekable(QObject *parent) : QObject(parent) { connect(Core(), &CutterCore::seekChanged, this, &CutterSeekable::onCoreSeekChanged); } @@ -38,7 +35,6 @@ void CutterSeekable::updateSeek(RVA addr, bool localOnly) emit seekableSeekChanged(addr); } - void CutterSeekable::seekPrev() { if (synchronized) { @@ -65,20 +61,19 @@ bool CutterSeekable::isSynchronized() void CutterSeekable::seekToReference(RVA offset) { - if (offset == RVA_INVALID) - { + if (offset == RVA_INVALID) { return; } - + RVA target; QList refs = Core()->getXRefs(offset, false, false); - + if (refs.length()) { if (refs.length() > 1) { qWarning() << tr("More than one (%1) references here. Weird behaviour expected.") - .arg(refs.length()); + .arg(refs.length()); } - + target = refs.at(0).to; if (target != RVA_INVALID) { seek(target); diff --git a/src/common/CutterSeekable.h b/src/common/CutterSeekable.h index ebaa61fc..b8663cbe 100644 --- a/src/common/CutterSeekable.h +++ b/src/common/CutterSeekable.h @@ -4,7 +4,7 @@ class MainWindow; -class CUTTER_EXPORT CutterSeekable : public QObject +class CUTTER_EXPORT CutterSeekable : public QObject { Q_OBJECT @@ -45,7 +45,8 @@ public: bool isSynchronized(); /** - * @brief seekToReference will seek to the function or the object which is referenced in a given offset + * @brief seekToReference will seek to the function or the object which is referenced in a given + * offset * @param offset - an address that contains a reference to jump to */ void seekToReference(RVA offset); diff --git a/src/common/Decompiler.cpp b/src/common/Decompiler.cpp index d6b3b065..569a7d68 100644 --- a/src/common/Decompiler.cpp +++ b/src/common/Decompiler.cpp @@ -6,19 +6,17 @@ #include Decompiler::Decompiler(const QString &id, const QString &name, QObject *parent) - : QObject(parent), - id(id), - name(name) + : QObject(parent), id(id), name(name) { } -RzAnnotatedCode *Decompiler::makeWarning(QString warningMessage){ +RzAnnotatedCode *Decompiler::makeWarning(QString warningMessage) +{ std::string temporary = warningMessage.toStdString(); return rz_annotated_code_new(strdup(temporary.c_str())); } -JSDecDecompiler::JSDecDecompiler(QObject *parent) - : Decompiler("jsdec", "jsdec", parent) +JSDecDecompiler::JSDecDecompiler(QObject *parent) : Decompiler("jsdec", "jsdec", parent) { task = nullptr; } diff --git a/src/common/Decompiler.h b/src/common/Decompiler.h index 2eaa9e28..c3468b1e 100644 --- a/src/common/Decompiler.h +++ b/src/common/Decompiler.h @@ -11,7 +11,7 @@ /** * Implements a decompiler that can be registered using CutterCore::registerDecompiler() */ -class CUTTER_EXPORT Decompiler: public QObject +class CUTTER_EXPORT Decompiler : public QObject { Q_OBJECT @@ -25,19 +25,19 @@ public: static RzAnnotatedCode *makeWarning(QString warningMessage); - QString getId() const { return id; } - QString getName() const { return name; } - virtual bool isRunning() { return false; } + QString getId() const { return id; } + QString getName() const { return name; } + virtual bool isRunning() { return false; } virtual bool isCancelable() { return false; } - virtual void decompileAt(RVA addr) =0; + virtual void decompileAt(RVA addr) = 0; virtual void cancel() {} signals: void finished(RzAnnotatedCode *codeDecompiled); }; -class JSDecDecompiler: public Decompiler +class JSDecDecompiler : public Decompiler { Q_OBJECT @@ -48,9 +48,9 @@ public: explicit JSDecDecompiler(QObject *parent = nullptr); void decompileAt(RVA addr) override; - bool isRunning() override { return task != nullptr; } + bool isRunning() override { return task != nullptr; } static bool isAvailable(); }; -#endif //DECOMPILER_H +#endif // DECOMPILER_H diff --git a/src/common/DecompilerHighlighter.cpp b/src/common/DecompilerHighlighter.cpp index f09cfe41..48183cc2 100644 --- a/src/common/DecompilerHighlighter.cpp +++ b/src/common/DecompilerHighlighter.cpp @@ -4,8 +4,7 @@ #include -DecompilerHighlighter::DecompilerHighlighter(QTextDocument *parent) - : QSyntaxHighlighter(parent) +DecompilerHighlighter::DecompilerHighlighter(QTextDocument *parent) : QSyntaxHighlighter(parent) { setupTheme(); connect(Config(), &Configuration::colorsUpdated, this, [this]() { @@ -21,18 +20,19 @@ void DecompilerHighlighter::setAnnotations(RzAnnotatedCode *code) void DecompilerHighlighter::setupTheme() { - struct { + struct + { RSyntaxHighlightType type; QString name; } mapping[] = { - {RZ_SYNTAX_HIGHLIGHT_TYPE_KEYWORD, "pop"}, - {RZ_SYNTAX_HIGHLIGHT_TYPE_COMMENT, "comment"}, - {RZ_SYNTAX_HIGHLIGHT_TYPE_DATATYPE, "func_var_type"}, - {RZ_SYNTAX_HIGHLIGHT_TYPE_FUNCTION_NAME, "fname"}, - {RZ_SYNTAX_HIGHLIGHT_TYPE_FUNCTION_PARAMETER, "args"}, - {RZ_SYNTAX_HIGHLIGHT_TYPE_LOCAL_VARIABLE, "func_var"}, - {RZ_SYNTAX_HIGHLIGHT_TYPE_CONSTANT_VARIABLE, "num"}, - {RZ_SYNTAX_HIGHLIGHT_TYPE_GLOBAL_VARIABLE, "flag"}, + { RZ_SYNTAX_HIGHLIGHT_TYPE_KEYWORD, "pop" }, + { RZ_SYNTAX_HIGHLIGHT_TYPE_COMMENT, "comment" }, + { RZ_SYNTAX_HIGHLIGHT_TYPE_DATATYPE, "func_var_type" }, + { RZ_SYNTAX_HIGHLIGHT_TYPE_FUNCTION_NAME, "fname" }, + { RZ_SYNTAX_HIGHLIGHT_TYPE_FUNCTION_PARAMETER, "args" }, + { RZ_SYNTAX_HIGHLIGHT_TYPE_LOCAL_VARIABLE, "func_var" }, + { RZ_SYNTAX_HIGHLIGHT_TYPE_CONSTANT_VARIABLE, "num" }, + { RZ_SYNTAX_HIGHLIGHT_TYPE_GLOBAL_VARIABLE, "flag" }, }; for (const auto &pair : mapping) { assert(pair.type < format.size()); @@ -49,10 +49,12 @@ void DecompilerHighlighter::highlightBlock(const QString &) size_t start = block.position(); size_t end = block.position() + block.length(); - std::unique_ptr annotations(rz_annotated_code_annotations_range(code, start, end), &rz_pvector_free); + std::unique_ptr annotations( + rz_annotated_code_annotations_range(code, start, end), &rz_pvector_free); void **iter; - rz_pvector_foreach(annotations.get(), iter) { - RzCodeAnnotation *annotation = static_cast(*iter); + rz_pvector_foreach(annotations.get(), iter) + { + RzCodeAnnotation *annotation = static_cast(*iter); if (annotation->type != RZ_CODE_ANNOTATION_TYPE_SYNTAX_HIGHLIGHT) { continue; } diff --git a/src/common/DecompilerHighlighter.h b/src/common/DecompilerHighlighter.h index 7ca96840..21ac364e 100644 --- a/src/common/DecompilerHighlighter.h +++ b/src/common/DecompilerHighlighter.h @@ -22,17 +22,17 @@ public: /** * @brief Set the code with annotations to be used for highlighting. - * + * * It is callers responsibility to ensure that it is synchronized with currentTextDocument and * has sufficiently long lifetime. - * - * @param code + * + * @param code */ void setAnnotations(RzAnnotatedCode *code); + protected: void highlightBlock(const QString &text) override; - private: void setupTheme(); diff --git a/src/common/DirectionalComboBox.cpp b/src/common/DirectionalComboBox.cpp index 9bf4de03..b2aa86b9 100644 --- a/src/common/DirectionalComboBox.cpp +++ b/src/common/DirectionalComboBox.cpp @@ -10,11 +10,9 @@ void DirectionalComboBox::showPopup() QComboBox::showPopup(); QWidget *popup = this->findChild(); if (popupUpwards) { - popup->move(popup->x(), - mapToGlobal(this->rect().bottomLeft()).y() - popup->height()); + popup->move(popup->x(), mapToGlobal(this->rect().bottomLeft()).y() - popup->height()); } else { - popup->move(popup->x(), - mapToGlobal(this->rect().topLeft()).y()); + popup->move(popup->x(), mapToGlobal(this->rect().topLeft()).y()); } } diff --git a/src/common/DirectionalComboBox.h b/src/common/DirectionalComboBox.h index 96bb315f..59a442af 100644 --- a/src/common/DirectionalComboBox.h +++ b/src/common/DirectionalComboBox.h @@ -3,7 +3,7 @@ #include /** * @brief Custom QComboBox created to prevent the menu popup from opening up at different - * offsets for different items, which may result in list items being rendered outside + * offsets for different items, which may result in list items being rendered outside * of the screen/containing widget. */ class DirectionalComboBox : public QComboBox @@ -20,4 +20,3 @@ private: void showPopup(); }; - diff --git a/src/common/FunctionsTask.h b/src/common/FunctionsTask.h index 5a2574a1..7de50877 100644 --- a/src/common/FunctionsTask.h +++ b/src/common/FunctionsTask.h @@ -7,10 +7,10 @@ class FunctionsTask : public AsyncTask { -Q_OBJECT + Q_OBJECT public: - QString getTitle() override { return tr("Fetching Functions"); } + QString getTitle() override { return tr("Fetching Functions"); } signals: void fetchFinished(const QList &strings); @@ -23,4 +23,4 @@ protected: } }; -#endif //FUNCTIONSTASK_H +#endif // FUNCTIONSTASK_H diff --git a/src/common/Helpers.cpp b/src/common/Helpers.cpp index 0e4e1d41..5cceaaca 100644 --- a/src/common/Helpers.cpp +++ b/src/common/Helpers.cpp @@ -18,10 +18,10 @@ static QAbstractItemView::ScrollMode scrollMode() { const bool use_scrollperpixel = true; - return use_scrollperpixel ? QAbstractItemView::ScrollPerPixel : QAbstractItemView::ScrollPerItem; + return use_scrollperpixel ? QAbstractItemView::ScrollPerPixel + : QAbstractItemView::ScrollPerItem; } - namespace qhelpers { QString formatBytecount(const uint64_t bytecount) @@ -31,12 +31,12 @@ QString formatBytecount(const uint64_t bytecount) } const int exp = log(bytecount) / log(1024); - constexpr char suffixes[] = {' ', 'k', 'M', 'G', 'T', 'P', 'E'}; + constexpr char suffixes[] = { ' ', 'k', 'M', 'G', 'T', 'P', 'E' }; QString str; QTextStream stream(&str); - stream << qSetRealNumberPrecision(3) << bytecount / pow(1024, exp) - << ' ' << suffixes[exp] << 'B'; + stream << qSetRealNumberPrecision(3) << bytecount / pow(1024, exp) << ' ' << suffixes[exp] + << 'B'; return stream.readAll(); } @@ -161,25 +161,24 @@ int getMaxFullyDisplayedLines(QTextEdit *textEdit) { QFontMetrics fontMetrics(textEdit->document()->defaultFont()); return (textEdit->height() - - (textEdit->contentsMargins().top() - + textEdit->contentsMargins().bottom() + - (textEdit->contentsMargins().top() + textEdit->contentsMargins().bottom() + (int)(textEdit->document()->documentMargin() * 2))) - / fontMetrics.lineSpacing(); + / fontMetrics.lineSpacing(); } int getMaxFullyDisplayedLines(QPlainTextEdit *plainTextEdit) { QFontMetrics fontMetrics(plainTextEdit->document()->defaultFont()); return (plainTextEdit->height() - - (plainTextEdit->contentsMargins().top() - + plainTextEdit->contentsMargins().bottom() + - (plainTextEdit->contentsMargins().top() + plainTextEdit->contentsMargins().bottom() + (int)(plainTextEdit->document()->documentMargin() * 2))) - / fontMetrics.lineSpacing(); + / fontMetrics.lineSpacing(); } QByteArray applyColorToSvg(const QByteArray &data, QColor color) { - static const QRegularExpression styleRegExp("(?:style=\".*fill:(.*?);.*?\")|(?:fill=\"(.*?)\")"); + static const QRegularExpression styleRegExp( + "(?:style=\".*fill:(.*?);.*?\")|(?:fill=\"(.*?)\")"); QString replaceStr = QString("#%1").arg(color.rgb() & 0xffffff, 6, 16, QLatin1Char('0')); int replaceStrLen = replaceStr.length(); @@ -194,7 +193,8 @@ QByteArray applyColorToSvg(const QByteArray &data, QColor color) } int captureIndex = match.captured(1).isNull() ? 2 : 1; - xml.replace(match.capturedStart(captureIndex), match.capturedLength(captureIndex), replaceStr); + xml.replace(match.capturedStart(captureIndex), match.capturedLength(captureIndex), + replaceStr); offset = match.capturedStart(captureIndex) + replaceStrLen; } @@ -210,11 +210,12 @@ QByteArray applyColorToSvg(const QString &filename, QColor color) } /** - * @brief finds the theme-specific icon path and calls `setter` functor providing a pointer of an object which has to be used - * and loaded icon + * @brief finds the theme-specific icon path and calls `setter` functor providing a pointer of an + * object which has to be used and loaded icon * @param supportedIconsNames list of * @param setter functor which has to be called - * for example we need to set an action icon, the functor can be just [](void* o, const QIcon &icon) { static_cast(o)->setIcon(icon); } + * for example we need to set an action icon, the functor can be just [](void* o, const QIcon + * &icon) { static_cast(o)->setIcon(icon); } */ void setThemeIcons(QList> supportedIconsNames, std::function setter) @@ -232,7 +233,7 @@ void setThemeIcons(QList> supportedIconsNames, iconPath = iconsDirPath; // Verify that indeed there is an alternative icon in this theme // Otherwise, fallback to the regular icon folder - if (QFile::exists(iconPath + relativeThemeDir + p.second)) { + if (QFile::exists(iconPath + relativeThemeDir + p.second)) { iconPath += relativeThemeDir; } setter(p.first, QIcon(iconPath + p.second)); @@ -272,11 +273,8 @@ void selectIndexByData(QComboBox *widget, QVariant data, int defaultIndex) void emitColumnChanged(QAbstractItemModel *model, int column) { if (model && model->rowCount()) { - emit model->dataChanged( - model->index(0, column), - model->index(model->rowCount() - 1, column), - { Qt::DisplayRole } - ); + emit model->dataChanged(model->index(0, column), + model->index(model->rowCount() - 1, column), { Qt::DisplayRole }); } } diff --git a/src/common/Helpers.h b/src/common/Helpers.h index c94d88e0..2a2da821 100644 --- a/src/common/Helpers.h +++ b/src/common/Helpers.h @@ -25,9 +25,9 @@ class QPaintDevice; class QComboBox; #if QT_VERSION < QT_VERSION_CHECK(5, 14, 0) -#define CUTTER_QT_SKIP_EMPTY_PARTS QString::SkipEmptyParts +# define CUTTER_QT_SKIP_EMPTY_PARTS QString::SkipEmptyParts #else -#define CUTTER_QT_SKIP_EMPTY_PARTS Qt::SkipEmptyParts +# define CUTTER_QT_SKIP_EMPTY_PARTS Qt::SkipEmptyParts #endif namespace qhelpers { @@ -35,15 +35,18 @@ CUTTER_EXPORT QString formatBytecount(const uint64_t bytecount); CUTTER_EXPORT void adjustColumns(QTreeView *tv, int columnCount, int padding); CUTTER_EXPORT void adjustColumns(QTreeWidget *tw, int padding); CUTTER_EXPORT bool selectFirstItem(QAbstractItemView *itemView); -CUTTER_EXPORT QTreeWidgetItem *appendRow(QTreeWidget *tw, const QString &str, const QString &str2 = QString(), - const QString &str3 = QString(), const QString &str4 = QString(), const QString &str5 = QString()); +CUTTER_EXPORT QTreeWidgetItem *appendRow(QTreeWidget *tw, const QString &str, + const QString &str2 = QString(), + const QString &str3 = QString(), + const QString &str4 = QString(), + const QString &str5 = QString()); CUTTER_EXPORT void setVerticalScrollMode(QAbstractItemView *tw); CUTTER_EXPORT void setCheckedWithoutSignals(QAbstractButton *button, bool checked); - -struct CUTTER_EXPORT SizePolicyMinMax { +struct CUTTER_EXPORT SizePolicyMinMax +{ QSizePolicy sizePolicy; int min; int max; @@ -61,7 +64,8 @@ CUTTER_EXPORT int getMaxFullyDisplayedLines(QPlainTextEdit *plainTextEdit); CUTTER_EXPORT QByteArray applyColorToSvg(const QByteArray &data, QColor color); CUTTER_EXPORT QByteArray applyColorToSvg(const QString &filename, QColor color); -CUTTER_EXPORT void setThemeIcons(QList> supportedIconsNames, std::function setter); +CUTTER_EXPORT void setThemeIcons(QList> supportedIconsNames, + std::function setter); CUTTER_EXPORT void prependQAction(QAction *action, QMenu *menu); CUTTER_EXPORT qreal devicePixelRatio(const QPaintDevice *p); @@ -73,7 +77,7 @@ CUTTER_EXPORT qreal devicePixelRatio(const QPaintDevice *p); */ CUTTER_EXPORT void selectIndexByData(QComboBox *comboBox, QVariant data, int defaultIndex = -1); /** - * @brief Emit data change signal in a model's column (DisplayRole) + * @brief Emit data change signal in a model's column (DisplayRole) * @param model - model containing data with changes * @param column - column in the model */ diff --git a/src/common/HighDpiPixmap.cpp b/src/common/HighDpiPixmap.cpp index c21cd2dd..bd7ca1be 100644 --- a/src/common/HighDpiPixmap.cpp +++ b/src/common/HighDpiPixmap.cpp @@ -16,8 +16,8 @@ static qreal GetDevicePixelRatio(qreal devicePixelRatio) } HighDpiPixmap::HighDpiPixmap(int width, int height, qreal devicePixelRatio) - : QPixmap(int(width * GetDevicePixelRatio(devicePixelRatio)), - int(height * GetDevicePixelRatio(devicePixelRatio))) + : QPixmap(int(width *GetDevicePixelRatio(devicePixelRatio)), + int(height *GetDevicePixelRatio(devicePixelRatio))) { setDevicePixelRatio(GetDevicePixelRatio(devicePixelRatio)); } diff --git a/src/common/Highlighter.cpp b/src/common/Highlighter.cpp index 44021b0a..5431a398 100644 --- a/src/common/Highlighter.cpp +++ b/src/common/Highlighter.cpp @@ -3,8 +3,7 @@ #include -Highlighter::Highlighter(QTextDocument *parent) : - QSyntaxHighlighter(parent) +Highlighter::Highlighter(QTextDocument *parent) : QSyntaxHighlighter(parent) { HighlightingRule rule; @@ -28,7 +27,6 @@ Highlighter::Highlighter(QTextDocument *parent) : highlightingRules.append(rule); } - singleLineCommentFormat.setFontWeight(QFont::Bold); singleLineCommentFormat.setForeground(QColor(63, 195, 128)); rule.pattern.setPattern(";[^\n]*"); @@ -57,17 +55,19 @@ void Highlighter::highlightBlock(const QString &text) startIndex = QRegularExpression(commentStartRegularExpression).match(text).capturedStart(); while (startIndex >= 0) { - QRegularExpressionMatch commentEndMatch = QRegularExpression(commentEndRegularExpression).match(text.mid(startIndex)); + QRegularExpressionMatch commentEndMatch = + QRegularExpression(commentEndRegularExpression).match(text.mid(startIndex)); int endIndex = commentEndMatch.capturedStart(); int commentLength; if (endIndex == -1) { setCurrentBlockState(1); commentLength = text.length() - startIndex; } else { - commentLength = endIndex - startIndex - + commentEndMatch.capturedLength(); + commentLength = endIndex - startIndex + commentEndMatch.capturedLength(); } setFormat(startIndex, commentLength, multiLineCommentFormat); - startIndex = QRegularExpression(commentStartRegularExpression).match(text.mid(startIndex + commentLength)).capturedStart(); + startIndex = QRegularExpression(commentStartRegularExpression) + .match(text.mid(startIndex + commentLength)) + .capturedStart(); } } diff --git a/src/common/Highlighter.h b/src/common/Highlighter.h index 31732047..bdf85dcd 100644 --- a/src/common/Highlighter.h +++ b/src/common/Highlighter.h @@ -24,7 +24,8 @@ protected: private: CutterCore *core; - struct HighlightingRule { + struct HighlightingRule + { QRegularExpression pattern; QTextCharFormat format; }; @@ -42,4 +43,4 @@ private: QTextCharFormat functionFormat; }; -#endif // HIGHLIGHTER_H +#endif // HIGHLIGHTER_H diff --git a/src/common/IOModesController.cpp b/src/common/IOModesController.cpp index a66e6065..e7a11aaf 100644 --- a/src/common/IOModesController.cpp +++ b/src/common/IOModesController.cpp @@ -51,17 +51,17 @@ bool IOModesController::prepareForWriting() QMessageBox msgBox; msgBox.setIcon(QMessageBox::Icon::Critical); msgBox.setWindowTitle(QObject::tr("Write error")); - msgBox.setText( - QObject::tr("Your file is opened in read-only mode. " - "Editing is only available when the file is opened in either Write or Cache modes.\n\n" - "WARNING: In Write mode, any changes will be committed to the file on disk. " - "For safety, please consider using Cache mode and then commit the changes manually " - "via File -> Commit modifications to disk.")); + msgBox.setText(QObject::tr( + "Your file is opened in read-only mode. " + "Editing is only available when the file is opened in either Write or Cache modes.\n\n" + "WARNING: In Write mode, any changes will be committed to the file on disk. " + "For safety, please consider using Cache mode and then commit the changes manually " + "via File -> Commit modifications to disk.")); msgBox.addButton(QObject::tr("Cancel"), QMessageBox::RejectRole); - QAbstractButton *reopenButton = msgBox.addButton(QObject::tr("Reopen in Write mode"), - QMessageBox::YesRole); - QAbstractButton *iocacheButton = msgBox.addButton(QObject::tr("Enable Cache mode"), - QMessageBox::YesRole); + QAbstractButton *reopenButton = + msgBox.addButton(QObject::tr("Reopen in Write mode"), QMessageBox::YesRole); + QAbstractButton *iocacheButton = + msgBox.addButton(QObject::tr("Enable Cache mode"), QMessageBox::YesRole); msgBox.exec(); @@ -95,10 +95,13 @@ bool IOModesController::askCommitUnsavedChanges() { // Check if there are uncommitted changes if (!allChangesComitted()) { - QMessageBox::StandardButton ret = QMessageBox::question(NULL, QObject::tr("Uncomitted changes"), - QObject::tr("It seems that you have changes or patches that are not committed to the file.\n" - "Do you want to commit them now?"), - (QMessageBox::StandardButtons)(QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel)); + QMessageBox::StandardButton ret = QMessageBox::question( + NULL, QObject::tr("Uncomitted changes"), + QObject::tr("It seems that you have changes or patches that are not committed to " + "the file.\n" + "Do you want to commit them now?"), + (QMessageBox::StandardButtons)(QMessageBox::Save | QMessageBox::Discard + | QMessageBox::Cancel)); if (ret == QMessageBox::Save) { Core()->commitWriteCache(); } else if (ret == QMessageBox::Discard) { diff --git a/src/common/InitialOptions.h b/src/common/InitialOptions.h index 6179db58..503ffdee 100644 --- a/src/common/InitialOptions.h +++ b/src/common/InitialOptions.h @@ -7,7 +7,8 @@ /** * @brief The CommandDescription struct is a pair of a Rizin command and its description */ -struct CommandDescription { +struct CommandDescription +{ QString command; QString description; }; @@ -37,10 +38,10 @@ struct InitialOptions QString pdbFile; QString script; - - QList analCmd = { {"aaa", "Auto analysis"} }; + + QList analCmd = { { "aaa", "Auto analysis" } }; QString shellcode; }; -#endif //CUTTER_INITIALOPTIONS_H +#endif // CUTTER_INITIALOPTIONS_H diff --git a/src/common/Json.h b/src/common/Json.h index f6ec8c62..a8ce6288 100644 --- a/src/common/Json.h +++ b/src/common/Json.h @@ -16,4 +16,4 @@ static inline RVA JsonValueGetRVA(const QJsonValue &value, RVA defaultValue = RV return ret; } -#endif //CUTTER_JSON_H +#endif // CUTTER_JSON_H diff --git a/src/common/JsonModel.cpp b/src/common/JsonModel.cpp index 60074e48..d46a6798 100644 --- a/src/common/JsonModel.cpp +++ b/src/common/JsonModel.cpp @@ -1,7 +1,6 @@ #include "JsonModel.h" -JsonModel::JsonModel(QObject *parent) : - QAbstractItemModel(parent) +JsonModel::JsonModel(QObject *parent) : QAbstractItemModel(parent) { mRootItem = new JsonTreeItem; mHeaders.append("key"); @@ -42,10 +41,8 @@ QVariant JsonModel::data(const QModelIndex &index, int role) const if (!index.isValid()) return QVariant(); - JsonTreeItem *item = static_cast(index.internalPointer()); - if (role == Qt::DisplayRole) { if (index.column() == 0) @@ -122,4 +119,3 @@ int JsonModel::columnCount(const QModelIndex &parent) const Q_UNUSED(parent) return 2; } - diff --git a/src/common/JsonModel.h b/src/common/JsonModel.h index 4c950a40..4b5c7cdd 100644 --- a/src/common/JsonModel.h +++ b/src/common/JsonModel.h @@ -28,6 +28,7 @@ public: int rowCount(const QModelIndex &parent = QModelIndex()) const Q_DECL_OVERRIDE; int columnCount(const QModelIndex &parent = QModelIndex()) const Q_DECL_OVERRIDE; ~JsonModel(); + private: JsonTreeItem *mRootItem; QJsonDocument mDocument; diff --git a/src/common/JsonTreeItem.cpp b/src/common/JsonTreeItem.cpp index 676fdc17..3a16dbd7 100644 --- a/src/common/JsonTreeItem.cpp +++ b/src/common/JsonTreeItem.cpp @@ -73,9 +73,9 @@ JsonTreeItem *JsonTreeItem::load(const QJsonValue &value, JsonTreeItem *parent) JsonTreeItem *rootItem = new JsonTreeItem(parent); rootItem->setKey("root"); - if ( value.isObject()) { + if (value.isObject()) { - //Get all QJsonValue childs + // Get all QJsonValue childs for (const QString &key : value.toObject().keys()) { QJsonValue v = value.toObject().value(key); JsonTreeItem *child = load(v, rootItem); @@ -84,8 +84,8 @@ JsonTreeItem *JsonTreeItem::load(const QJsonValue &value, JsonTreeItem *parent) rootItem->appendChild(child); } - } else if ( value.isArray()) { - //Get all QJsonValue childs + } else if (value.isArray()) { + // Get all QJsonValue childs int index = 0; for (const QJsonValue &v : value.toArray()) { diff --git a/src/common/LinkedListPool.h b/src/common/LinkedListPool.h index 627e1ed9..53cd6dd7 100644 --- a/src/common/LinkedListPool.h +++ b/src/common/LinkedListPool.h @@ -8,20 +8,23 @@ /** * @brief Pool of singly linked lists. * - * Should not be used as general purpose container. Use only for algorithms that require linked lists ability - * to split and concatenate them. All the data is owned by LinkedListPool. + * Should not be used as general purpose container. Use only for algorithms that require linked + * lists ability to split and concatenate them. All the data is owned by LinkedListPool. * - * In contrast to std::list and std::forward_list doesn't allocate each node separately. LinkedListPool can reserve - * all the memory for multiple lists during construction. Uses std::vector as backing container. + * In contrast to std::list and std::forward_list doesn't allocate each node separately. + * LinkedListPool can reserve all the memory for multiple lists during construction. Uses + * std::vector as backing container. */ template class LinkedListPool { using IndexType = size_t; - struct Item { + struct Item + { IndexType next; T value; }; + public: /** * @brief List iterator. @@ -32,27 +35,19 @@ public: { IndexType index = 0; LinkedListPool *pool = nullptr; - ListIterator(IndexType index, LinkedListPool *pool) - : index(index) - , pool(pool) - {} + ListIterator(IndexType index, LinkedListPool *pool) : index(index), pool(pool) {} friend class LinkedListPool; + public: using iterator_category = std::forward_iterator_tag; using value_type = T; using difference_type = size_t; - using pointer = T*; - using reference = T&; + using pointer = T *; + using reference = T &; ListIterator() = default; - reference operator*() - { - return pool->data[index].value; - } - pointer operator->() - { - return &pool->data[index].value; - } + reference operator*() { return pool->data[index].value; } + pointer operator->() { return &pool->data[index].value; } ListIterator &operator++() { @@ -65,24 +60,18 @@ public: operator++(); return tmp; } - bool operator!=(const ListIterator &b) const - { - return index != b.index || pool != b.pool; - }; + bool operator!=(const ListIterator &b) const { return index != b.index || pool != b.pool; }; /** * @brief Test if iterator points to valid value. */ - explicit operator bool() const - { - return index; - } + explicit operator bool() const { return index; } }; /** * @brief Single list within LinkedListPool. * - * List only refers to chain of elements. Copying it doesn't copy any element. Item data is owned by - * LinkedListPool. + * List only refers to chain of elements. Copying it doesn't copy any element. Item data is + * owned by LinkedListPool. * * Use LinkedListPool::makeList to create non-empty list. */ @@ -91,28 +80,22 @@ public: IndexType head = 0; IndexType tail = 0; friend class LinkedListPool; - List(IndexType head, IndexType tail) - : head(head) - , tail(tail) - {} + List(IndexType head, IndexType tail) : head(head), tail(tail) {} + public: /** * @brief Create an empty list */ List() = default; - bool isEmpty() const - { - return head == 0; - } + bool isEmpty() const { return head == 0; } }; /** * @brief Create a linked list pool with capacity for \a initialCapacity list items. * @param initialCapacity number of elements to preallocate. */ - LinkedListPool(size_t initialCapacity) - : data(1) + LinkedListPool(size_t initialCapacity) : data(1) { data.reserve(initialCapacity + 1); // [0] element reserved } @@ -120,22 +103,23 @@ public: /** * @brief Create a list containing single item. * - * Does not invalidate any iterators, but may cause item relocation when initialCapacity is exceeded. + * Does not invalidate any iterators, but may cause item relocation when initialCapacity is + * exceeded. * @param value value of element that will be inserted in the created list * @return List containing single value \a value . */ List makeList(const T &value) { size_t position = data.size(); - data.push_back(Item{0, value}); - return {position, position}; + data.push_back(Item { 0, value }); + return { position, position }; } /** * @brief Split list and return second half. * - * After performing the operation, list passed as argument and return list point to the same items. Modifying them - * will affect both lists. + * After performing the operation, list passed as argument and return list point to the same + * items. Modifying them will affect both lists. * * @param list The list that needs to be split. * @param head Iterator to the first item in new list. Needs to be within \a list . @@ -143,14 +127,15 @@ public: */ List splitTail(const List &list, const ListIterator &head) { - return List {head.index, list.tail}; + return List { head.index, list.tail }; } /** * @brief Split list and return first half. * * @param list The list that needs to be split. - * @param end Iterator to the first item that should not be included in returned list. Needs to be within \a list . + * @param end Iterator to the first item that should not be included in returned list. Needs to + * be within \a list . * @return Returns prefix of \a list. */ List splitHead(const List &list, const ListIterator &end) @@ -166,7 +151,7 @@ public: last = data[last].next; } data[last].next = 0; - return List {list.head, last}; + return List { list.head, last }; } /** @@ -174,15 +159,9 @@ public: * @param list * @return Iterator pointing to the first item in the list. */ - ListIterator head(const List &list) - { - return iteratorFromIndex(list.head); - } + ListIterator head(const List &list) { return iteratorFromIndex(list.head); } - ListIterator end(const List &list) - { - return std::next(iteratorFromIndex(list.tail)); - } + ListIterator end(const List &list) { return std::next(iteratorFromIndex(list.tail)); } List append(const List &head, const List &tail) { @@ -192,18 +171,15 @@ public: if (tail.isEmpty()) { return head; } - List result{head.head, tail.tail}; + List result { head.head, tail.tail }; data[head.tail].next = tail.head; return result; } + private: - ListIterator iteratorFromIndex(IndexType index) - { - return ListIterator{ index, this }; - } + ListIterator iteratorFromIndex(IndexType index) { return ListIterator { index, this }; } std::vector data; }; - #endif // LINKED_LIST_POOL diff --git a/src/common/MdHighlighter.cpp b/src/common/MdHighlighter.cpp index 9d6bacc4..c399da80 100644 --- a/src/common/MdHighlighter.cpp +++ b/src/common/MdHighlighter.cpp @@ -2,8 +2,7 @@ #include "common/MdHighlighter.h" -MdHighlighter::MdHighlighter(QTextDocument *parent) - : QSyntaxHighlighter(parent) +MdHighlighter::MdHighlighter(QTextDocument *parent) : QSyntaxHighlighter(parent) { HighlightingRule rule; @@ -11,8 +10,10 @@ MdHighlighter::MdHighlighter(QTextDocument *parent) keywordFormat.setFontWeight(QFont::Bold); QStringList keywordPatterns; - keywordPatterns << "^\\#{1,6}[ A-Za-z]+\\b" << "\\*\\*([^\\\\]+)\\*\\*" - << "\\*([^\\\\]+)\\*" << "\\_([^\\\\]+)\\_" + keywordPatterns << "^\\#{1,6}[ A-Za-z]+\\b" + << "\\*\\*([^\\\\]+)\\*\\*" + << "\\*([^\\\\]+)\\*" + << "\\_([^\\\\]+)\\_" << "\\_\\_([^\\\\]+)\\_\\_"; for (const QString &pattern : keywordPatterns) { diff --git a/src/common/MdHighlighter.h b/src/common/MdHighlighter.h index 71fcf424..951ffd55 100644 --- a/src/common/MdHighlighter.h +++ b/src/common/MdHighlighter.h @@ -20,7 +20,8 @@ protected: void highlightBlock(const QString &text); private: - struct HighlightingRule { + struct HighlightingRule + { QRegularExpression pattern; QTextCharFormat format; }; @@ -34,4 +35,4 @@ private: QTextCharFormat functionFormat; }; -#endif // MDHIGHLIGHTER_H +#endif // MDHIGHLIGHTER_H diff --git a/src/common/Metrics.h b/src/common/Metrics.h index e7abc827..0c2afbc1 100644 --- a/src/common/Metrics.h +++ b/src/common/Metrics.h @@ -9,18 +9,23 @@ class QRectF; class QFontMetrics; class QFontMetricsF; -template struct Metrics {}; +template +struct Metrics +{ +}; -template<> struct Metrics +template<> +struct Metrics { using Rect = QRect; using FontMetrics = QFontMetrics; }; -template<> struct Metrics +template<> +struct Metrics { using Rect = QRectF; using FontMetrics = QFontMetricsF; }; -#endif //METRICS_H +#endif // METRICS_H diff --git a/src/common/ProgressIndicator.cpp b/src/common/ProgressIndicator.cpp index e28b1b96..b827eed1 100644 --- a/src/common/ProgressIndicator.cpp +++ b/src/common/ProgressIndicator.cpp @@ -9,15 +9,12 @@ static const int paddingInner = 8; static const int arms = 12; static const int timerInterval = 50; -ProgressIndicator::ProgressIndicator(QWidget *parent) - : QWidget(parent) +ProgressIndicator::ProgressIndicator(QWidget *parent) : QWidget(parent) { updateAnimationTimer(); } -ProgressIndicator::~ProgressIndicator() -{ -} +ProgressIndicator::~ProgressIndicator() {} void ProgressIndicator::setProgressIndicatorVisible(bool visible) { @@ -77,13 +74,9 @@ void ProgressIndicator::paintEvent(QPaintEvent *) QLineF line(paddingInner, 0.0, width() * 0.5 - paddingOuter, 0.0); qreal angle = 360.0 / arms; - for (int i=0; i -class ProgressIndicator: public QWidget +class ProgressIndicator : public QWidget { public: ProgressIndicator(QWidget *parent = nullptr); @@ -13,10 +13,10 @@ public: QSize minimumSizeHint() const override; QSize sizeHint() const override; - bool getProgressIndicatorVisible() const { return progressIndicatorVisible; } + bool getProgressIndicatorVisible() const { return progressIndicatorVisible; } void setProgressIndicatorVisible(bool visible); - bool getAnimating() const { return animating; } + bool getAnimating() const { return animating; } void setAnimating(bool animating); protected: @@ -33,5 +33,4 @@ private: void updateAnimationTimer(); }; - -#endif //PROGRESSINDICATOR_H +#endif // PROGRESSINDICATOR_H diff --git a/src/common/PythonAPI.cpp b/src/common/PythonAPI.cpp index b54fe06f..dcad8e08 100644 --- a/src/common/PythonAPI.cpp +++ b/src/common/PythonAPI.cpp @@ -16,7 +16,7 @@ PyObject *api_cmd(PyObject *self, PyObject *args) { Q_UNUSED(self); char *command; - char *result = (char *) ""; + char *result = (char *)""; QString cmdRes; QByteArray cmdBytes; if (PyArg_ParseTuple(args, "s:command", &command)) { @@ -41,9 +41,8 @@ PyObject *api_message(PyObject *self, PyObject *args, PyObject *kwargs) char *message; int debug = 0; static const char *kwlist[] = { "", "debug", NULL }; - if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|i", - const_cast(kwlist), - &message, &debug)) { + if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|i", const_cast(kwlist), &message, + &debug)) { return NULL; } Core()->message(QString(message), debug); @@ -52,28 +51,16 @@ PyObject *api_message(PyObject *self, PyObject *args, PyObject *kwargs) } PyMethodDef CutterMethods[] = { - { - "version", api_version, METH_NOARGS, - "Returns Cutter current version" - }, - { - "cmd", api_cmd, METH_VARARGS, - "Execute a command inside Cutter" - }, - { - "refresh", api_refresh, METH_NOARGS, - "Refresh Cutter widgets" - }, - { - "message", (PyCFunction)(void *)/* don't remove this double cast! */api_message, METH_VARARGS | METH_KEYWORDS, - "Print message" - }, - {NULL, NULL, 0, NULL} + { "version", api_version, METH_NOARGS, "Returns Cutter current version" }, + { "cmd", api_cmd, METH_VARARGS, "Execute a command inside Cutter" }, + { "refresh", api_refresh, METH_NOARGS, "Refresh Cutter widgets" }, + { "message", (PyCFunction)(void *)/* don't remove this double cast! */ api_message, + METH_VARARGS | METH_KEYWORDS, "Print message" }, + { NULL, NULL, 0, NULL } }; PyModuleDef CutterModule = { - PyModuleDef_HEAD_INIT, "_cutter", NULL, -1, CutterMethods, - NULL, NULL, NULL, NULL + PyModuleDef_HEAD_INIT, "_cutter", NULL, -1, CutterMethods, NULL, NULL, NULL, NULL }; PyObject *PyInit_api() diff --git a/src/common/PythonManager.cpp b/src/common/PythonManager.cpp index 79564ab6..5b2ecd16 100644 --- a/src/common/PythonManager.cpp +++ b/src/common/PythonManager.cpp @@ -11,9 +11,9 @@ #include #ifdef CUTTER_ENABLE_PYTHON_BINDINGS -#include -#include -#include +# include +# include +# include #endif #include "QtResImporter.h" @@ -28,29 +28,25 @@ PythonManager *PythonManager::getInstance() return uniqueInstance; } -PythonManager::PythonManager() -{ -} +PythonManager::PythonManager() {} -PythonManager::~PythonManager() -{ -} +PythonManager::~PythonManager() {} void PythonManager::initPythonHome() { #if defined(APPIMAGE) || defined(MACOS_PYTHON_FRAMEWORK_BUNDLED) if (customPythonHome.isNull()) { auto pythonHomeDir = QDir(QCoreApplication::applicationDirPath()); -# ifdef APPIMAGE +# ifdef APPIMAGE // Executable is in appdir/bin pythonHomeDir.cdUp(); qInfo() << "Setting PYTHONHOME =" << pythonHomeDir.absolutePath() << " for AppImage."; -# else // MACOS_PYTHON_FRAMEWORK_BUNDLED +# else // MACOS_PYTHON_FRAMEWORK_BUNDLED // @executable_path/../Frameworks/Python.framework/Versions/Current pythonHomeDir.cd("../Frameworks/Python.framework/Versions/Current"); - qInfo() << "Setting PYTHONHOME =" << pythonHomeDir.absolutePath() << - " for macOS Application Bundle."; -# endif + qInfo() << "Setting PYTHONHOME =" << pythonHomeDir.absolutePath() + << " for macOS Application Bundle."; +# endif customPythonHome = pythonHomeDir.absolutePath(); } #endif @@ -85,11 +81,11 @@ void PythonManager::initialize() } #ifdef CUTTER_ENABLE_PYTHON_BINDINGS -static void pySideDestructionVisitor(SbkObject* pyObj, void* data) +static void pySideDestructionVisitor(SbkObject *pyObj, void *data) { - void **realData = reinterpret_cast(data); - auto pyQApp = reinterpret_cast(realData[0]); - auto pyQObjectType = reinterpret_cast(realData[1]); + void **realData = reinterpret_cast(data); + auto pyQApp = reinterpret_cast(realData[0]); + auto pyQObjectType = reinterpret_cast(realData[1]); if (pyObj == pyQApp || !PyObject_TypeCheck(pyObj, pyQObjectType)) { return; @@ -112,8 +108,8 @@ static void pySideDestructionVisitor(SbkObject* pyObj, void* data) } Shiboken::Object::setValidCpp(pyObj, false); - Py_BEGIN_ALLOW_THREADS - Shiboken::callCppDestructor(Shiboken::Object::cppPointer(pyObj, pyQObjectType)); + Py_BEGIN_ALLOW_THREADS Shiboken::callCppDestructor( + Shiboken::Object::cppPointer(pyObj, pyQObjectType)); Py_END_ALLOW_THREADS }; #endif @@ -125,15 +121,16 @@ void PythonManager::shutdown() restoreThread(); #ifdef CUTTER_ENABLE_PYTHON_BINDINGS - // This is necessary to prevent a segfault when the CutterCore instance is deleted after the Shiboken::BindingManager + // This is necessary to prevent a segfault when the CutterCore instance is deleted after the + // Shiboken::BindingManager Core()->setProperty("_PySideInvalidatePtr", QVariant()); // see PySide::destroyQCoreApplication() PySide::SignalManager::instance().clear(); - Shiboken::BindingManager& bm = Shiboken::BindingManager::instance(); - SbkObject* pyQApp = bm.retrieveWrapper(QCoreApplication::instance()); - PyTypeObject* pyQObjectType = Shiboken::Conversions::getPythonTypeObject("QObject*"); - void* data[2] = {pyQApp, pyQObjectType}; + Shiboken::BindingManager &bm = Shiboken::BindingManager::instance(); + SbkObject *pyQApp = bm.retrieveWrapper(QCoreApplication::instance()); + PyTypeObject *pyQObjectType = Shiboken::Conversions::getPythonTypeObject("QObject*"); + void *data[2] = { pyQApp, pyQObjectType }; bm.visitAllPyObjects(&pySideDestructionVisitor, &data); PySide::runCleanupFunctions(); @@ -146,7 +143,8 @@ void PythonManager::shutdown() Py_Finalize(); } -void PythonManager::addPythonPath(char *path) { +void PythonManager::addPythonPath(char *path) +{ restoreThread(); PyObject *sysModule = PyImport_ImportModule("sys"); diff --git a/src/common/PythonManager.h b/src/common/PythonManager.h index 9c94c76c..ede09b13 100644 --- a/src/common/PythonManager.h +++ b/src/common/PythonManager.h @@ -3,12 +3,12 @@ #ifdef CUTTER_ENABLE_PYTHON -#include +# include typedef struct _ts PyThreadState; typedef struct _object PyObject; -class PythonManager: public QObject +class PythonManager : public QObject { Q_OBJECT @@ -37,8 +37,8 @@ public: class ThreadHolder { public: - ThreadHolder() { getInstance()->restoreThread(); } - ~ThreadHolder() { getInstance()->saveThread(); } + ThreadHolder() { getInstance()->restoreThread(); } + ~ThreadHolder() { getInstance()->saveThread(); } }; signals: @@ -51,7 +51,7 @@ private: int pyThreadStateCounter = 0; }; -#define Python() (PythonManager::getInstance()) +# define Python() (PythonManager::getInstance()) #endif // CUTTER_ENABLE_PYTHON diff --git a/src/common/QtResImporter.cpp b/src/common/QtResImporter.cpp index 425da707..04e97d34 100644 --- a/src/common/QtResImporter.cpp +++ b/src/common/QtResImporter.cpp @@ -23,9 +23,8 @@ PyObject *QtResGetCode(const char *name) QByteArray data = moduleFile.readAll(); moduleFile.close(); - PyObject *codeObject = Py_CompileString(data.constData(), - moduleFile.fileName().toLocal8Bit().constData(), - Py_file_input); + PyObject *codeObject = Py_CompileString( + data.constData(), moduleFile.fileName().toLocal8Bit().constData(), Py_file_input); if (!codeObject) { qWarning() << "Couldn't compile " << moduleFile.fileName(); } @@ -68,15 +67,12 @@ PyObject *qtres_get_code(PyObject *self, PyObject *args) Py_RETURN_NONE; } -PyMethodDef QtResMethods[] = { - { "exists", qtres_exists, METH_VARARGS, NULL }, - { "get_code", qtres_get_code, METH_VARARGS, NULL }, - {NULL, NULL, 0, NULL} -}; +PyMethodDef QtResMethods[] = { { "exists", qtres_exists, METH_VARARGS, NULL }, + { "get_code", qtres_get_code, METH_VARARGS, NULL }, + { NULL, NULL, 0, NULL } }; PyModuleDef QtResModule = { - PyModuleDef_HEAD_INIT, "_qtres", NULL, -1, QtResMethods, - NULL, NULL, NULL, NULL + PyModuleDef_HEAD_INIT, "_qtres", NULL, -1, QtResMethods, NULL, NULL, NULL, NULL }; PyObject *PyInit_qtres() diff --git a/src/common/RefreshDeferrer.cpp b/src/common/RefreshDeferrer.cpp index 3cf4c4e6..aab920ae 100644 --- a/src/common/RefreshDeferrer.cpp +++ b/src/common/RefreshDeferrer.cpp @@ -2,8 +2,8 @@ #include "RefreshDeferrer.h" #include "widgets/CutterDockWidget.h" -RefreshDeferrer::RefreshDeferrer(RefreshDeferrerAccumulator *acc, QObject *parent) : QObject(parent), - acc(acc) +RefreshDeferrer::RefreshDeferrer(RefreshDeferrerAccumulator *acc, QObject *parent) + : QObject(parent), acc(acc) { } @@ -41,4 +41,3 @@ void RefreshDeferrer::registerFor(CutterDockWidget *dockWidget) } }); } - diff --git a/src/common/RefreshDeferrer.h b/src/common/RefreshDeferrer.h index 56737a51..0a008973 100644 --- a/src/common/RefreshDeferrer.h +++ b/src/common/RefreshDeferrer.h @@ -24,33 +24,33 @@ protected: /** * @brief Add a new param to the accumulator */ - virtual void accumulate(RefreshDeferrerParams params) =0; + virtual void accumulate(RefreshDeferrerParams params) = 0; /** * @brief Ignore the incoming params. Useful for freeing if necessary. */ - virtual void ignoreParams(RefreshDeferrerParams params) =0; + virtual void ignoreParams(RefreshDeferrerParams params) = 0; /** * @brief Clear the current accumulator */ - virtual void clear() =0; + virtual void clear() = 0; /** * @brief Return the final result of the accumulation */ - virtual RefreshDeferrerParamsResult result() =0; + virtual RefreshDeferrerParamsResult result() = 0; }; - /** * @brief Accumulator which simply replaces the current value by an incoming new one * @tparam T The type of the param to store * - * This accumulator takes the ownership of all params passed to it and deletes them automatically if not needed anymore! + * This accumulator takes the ownership of all params passed to it and deletes them automatically if + * not needed anymore! */ template -class ReplacingRefreshDeferrerAccumulator: public RefreshDeferrerAccumulator +class ReplacingRefreshDeferrerAccumulator : public RefreshDeferrerAccumulator { private: T *value = nullptr; @@ -58,16 +58,16 @@ private: public: /** - * \param Determines whether, if nullptr is passed, the current value should be replaced or kept. + * \param Determines whether, if nullptr is passed, the current value should be replaced or + * kept. */ explicit ReplacingRefreshDeferrerAccumulator(bool replaceIfNull = true) - : replaceIfNull(replaceIfNull) {} - - ~ReplacingRefreshDeferrerAccumulator() override + : replaceIfNull(replaceIfNull) { - delete value; } + ~ReplacingRefreshDeferrerAccumulator() override { delete value; } + protected: void accumulate(RefreshDeferrerParams params) override { @@ -78,10 +78,7 @@ protected: value = static_cast(params); } - void ignoreParams(RefreshDeferrerParams params) override - { - delete static_cast(params); - } + void ignoreParams(RefreshDeferrerParams params) override { delete static_cast(params); } void clear() override { @@ -89,25 +86,22 @@ protected: value = nullptr; } - virtual RefreshDeferrerParamsResult result() override - { - return value; - } + virtual RefreshDeferrerParamsResult result() override { return value; } }; /** * @brief Helper class for deferred refreshing in Widgets * - * This class can handle the logic necessary to defer the refreshing of widgets when they are not visible. - * It contains an optional RefreshDeferrerAccumulator, which can be used to accumulate incoming events while - * refreshing is deferred. + * This class can handle the logic necessary to defer the refreshing of widgets when they are not + * visible. It contains an optional RefreshDeferrerAccumulator, which can be used to accumulate + * incoming events while refreshing is deferred. * * Example (don't write it like this in practice, use the convenience methods in CutterDockWidget): * ``` * // in the constructor of a widget - * this->refreshDeferrer = new RefreshDeferrer(new ReplacingRefreshDeferrerAccumulator(false), this); - * this->refreshDeferrer->registerFor(this); - * connect(this->refreshDeferrer, &RefreshDeferrer::refreshNow, this, [this](MyParam *param) { + * this->refreshDeferrer = new RefreshDeferrer(new ReplacingRefreshDeferrerAccumulator(false), + * this); this->refreshDeferrer->registerFor(this); connect(this->refreshDeferrer, + * &RefreshDeferrer::refreshNow, this, [this](MyParam *param) { * // We attempted a refresh some time before, but it got deferred. * // Now the RefreshDeferrer tells us to do the refresh and gives us the accumulated param. * this->doRefresh(*param); @@ -151,4 +145,4 @@ signals: void refreshNow(const RefreshDeferrerParamsResult paramsResult); }; -#endif //REFRESHDEFERRER_H +#endif // REFRESHDEFERRER_H diff --git a/src/common/ResourcePaths.cpp b/src/common/ResourcePaths.cpp index 03905a4b..2b0a5ee4 100644 --- a/src/common/ResourcePaths.cpp +++ b/src/common/ResourcePaths.cpp @@ -6,7 +6,6 @@ #include #include - #ifdef APPIMAGE static QDir appimageRoot() { @@ -37,7 +36,8 @@ static QStringList substitutePaths(const QStringList &paths) QStringList result; result.reserve(paths.size()); for (auto &path : paths) { - // consider ignoring some of system folders for portable packages here or standardLocations if it depends on path type + // consider ignoring some of system folders for portable packages here or standardLocations + // if it depends on path type result.push_back(substitutePath(path)); } return result; @@ -46,8 +46,8 @@ static QStringList substitutePaths(const QStringList &paths) QStringList Cutter::locateAll(QStandardPaths::StandardLocation type, const QString &fileName, QStandardPaths::LocateOptions options) { - // This function is reimplemented here instead of forwarded to Qt becauase existence check needs to be done - // after substitutions + // This function is reimplemented here instead of forwarded to Qt becauase existence check needs + // to be done after substitutions QStringList result; for (auto path : standardLocations(type)) { QString filePath = path + QLatin1Char('/') + fileName; @@ -81,4 +81,3 @@ QStringList Cutter::getTranslationsDirectories() result << QLibraryInfo::location(QLibraryInfo::TranslationsPath); return result; } - diff --git a/src/common/ResourcePaths.h b/src/common/ResourcePaths.h index 41c3cdca..f3622ff1 100644 --- a/src/common/ResourcePaths.h +++ b/src/common/ResourcePaths.h @@ -11,14 +11,11 @@ */ namespace Cutter { -QStringList locateAll( - QStandardPaths::StandardLocation type, - const QString &fileName, - QStandardPaths::LocateOptions options = QStandardPaths::LocateFile); +QStringList locateAll(QStandardPaths::StandardLocation type, const QString &fileName, + QStandardPaths::LocateOptions options = QStandardPaths::LocateFile); QStringList standardLocations(QStandardPaths::StandardLocation type); QString writableLocation(QStandardPaths::StandardLocation type); - /** * @brief Get list of available translation directories (depends on configuration and OS) * @return list of directories diff --git a/src/common/RichTextPainter.cpp b/src/common/RichTextPainter.cpp index 009285ae..83ad353f 100644 --- a/src/common/RichTextPainter.cpp +++ b/src/common/RichTextPainter.cpp @@ -6,12 +6,11 @@ #include #include -//TODO: fix performance (possibly use QTextLayout?) - +// TODO: fix performance (possibly use QTextLayout?) template void RichTextPainter::paintRichText(QPainter *painter, T x, T y, T w, T h, T xinc, - const List &richText, CachedFontMetrics *fontMetrics) + const List &richText, CachedFontMetrics *fontMetrics) { QPen pen; QPen highlightPen; @@ -21,24 +20,24 @@ void RichTextPainter::paintRichText(QPainter *painter, T x, T y, T w, T h, T xin T backgroundWidth = textWidth; if (backgroundWidth + xinc > w) backgroundWidth = w - xinc; - if (backgroundWidth <= 0) //stop drawing when going outside the specified width + if (backgroundWidth <= 0) // stop drawing when going outside the specified width break; switch (curRichText.flags) { - case FlagNone: //defaults + case FlagNone: // defaults pen.setColor(ConfigColor("btext").name()); painter->setPen(pen); break; - case FlagColor: //color only + case FlagColor: // color only pen.setColor(curRichText.textColor); painter->setPen(pen); break; - case FlagBackground: //background only + case FlagBackground: // background only if (backgroundWidth > 0 && curRichText.textBackground.alpha()) { brush.setColor(curRichText.textBackground); painter->fillRect(QRectF(x + xinc, y, backgroundWidth, h), brush); } break; - case FlagAll: //color+background + case FlagAll: // color+background if (backgroundWidth > 0 && curRichText.textBackground.alpha()) { brush.setColor(curRichText.textBackground); painter->fillRect(QRectF(x + xinc, y, backgroundWidth, h), brush); @@ -52,67 +51,74 @@ void RichTextPainter::paintRichText(QPainter *painter, T x, T y, T w, T h, T xin flags = Qt::TextBypassShaping; #endif - painter->drawText(typename Metrics::Rect(x + xinc, y, w - xinc, h), flags, curRichText.text); + painter->drawText(typename Metrics::Rect(x + xinc, y, w - xinc, h), flags, + curRichText.text); if (curRichText.highlight && curRichText.highlightColor.alpha()) { highlightPen.setColor(curRichText.highlightColor); highlightPen.setWidth(curRichText.highlightWidth); painter->setPen(highlightPen); T highlightOffsetX = curRichText.highlightConnectPrev ? -1 : 1; - painter->drawLine(x + xinc + highlightOffsetX, y + h - 1, x + xinc + backgroundWidth - 1, - y + h - 1); + painter->drawLine(x + xinc + highlightOffsetX, y + h - 1, + x + xinc + backgroundWidth - 1, y + h - 1); } xinc += textWidth; } } -template -void RichTextPainter::paintRichText(QPainter *painter, qreal x, qreal y, qreal w, qreal h, qreal xinc, - const List &richText, CachedFontMetrics *fontMetrics); - +template void RichTextPainter::paintRichText(QPainter *painter, qreal x, qreal y, qreal w, + qreal h, qreal xinc, const List &richText, + CachedFontMetrics *fontMetrics); /** - * @brief RichTextPainter::htmlRichText Convert rich text in x64dbg to HTML, for use by other applications + * @brief RichTextPainter::htmlRichText Convert rich text in x64dbg to HTML, for use by other + * applications * @param richText The rich text to be converted to HTML format - * @param textHtml The HTML source. Any previous content will be preserved and new content will be appended at the end. - * @param textPlain The plain text. Any previous content will be preserved and new content will be appended at the end. + * @param textHtml The HTML source. Any previous content will be preserved and new content will be + * appended at the end. + * @param textPlain The plain text. Any previous content will be preserved and new content will be + * appended at the end. */ void RichTextPainter::htmlRichText(const List &richText, QString &textHtml, QString &textPlain) { for (const CustomRichText_t &curRichText : richText) { - if (curRichText.text == " ") { //blank + if (curRichText.text == " ") { // blank textHtml += " "; textPlain += " "; continue; } switch (curRichText.flags) { - case FlagNone: //defaults + case FlagNone: // defaults textHtml += ""; break; - case FlagColor: //color only + case FlagColor: // color only textHtml += QString("").arg(curRichText.textColor.name()); break; - case FlagBackground: //background only - if (curRichText.textBackground != - Qt::transparent) // QColor::name() returns "#000000" for transparent color. That's not desired. Leave it blank. - textHtml += QString("").arg(curRichText.textBackground.name()); + case FlagBackground: // background only + if (curRichText.textBackground + != Qt::transparent) // QColor::name() returns "#000000" for transparent color. + // That's not desired. Leave it blank. + textHtml += QString("") + .arg(curRichText.textBackground.name()); else textHtml += QString(""); break; - case FlagAll: //color+background - if (curRichText.textBackground != - Qt::transparent) // QColor::name() returns "#000000" for transparent color. That's not desired. Leave it blank. - textHtml += QString("").arg( - curRichText.textColor.name(), curRichText.textBackground.name()); + case FlagAll: // color+background + if (curRichText.textBackground + != Qt::transparent) // QColor::name() returns "#000000" for transparent color. + // That's not desired. Leave it blank. + textHtml += QString("") + .arg(curRichText.textColor.name(), + curRichText.textBackground.name()); else textHtml += QString("").arg(curRichText.textColor.name()); break; } - if (curRichText.highlight) //Underline highlighted token + if (curRichText.highlight) // Underline highlighted token textHtml += ""; textHtml += curRichText.text.toHtmlEscaped(); if (curRichText.highlight) textHtml += ""; - textHtml += ""; //Close the tag + textHtml += ""; // Close the tag textPlain += curRichText.text; } } @@ -185,7 +191,8 @@ RichTextPainter::List RichTextPainter::cropped(const RichTextPainter::List &rich auto &text = r.back(); if (text.text.length() >= indicatorCropLength) { - text.text.replace(text.text.length() - indicatorCropLength, indicatorCropLength, indicator); + text.text.replace(text.text.length() - indicatorCropLength, indicatorCropLength, + indicator); break; } diff --git a/src/common/RichTextPainter.h b/src/common/RichTextPainter.h index e50492db..b0f0f180 100644 --- a/src/common/RichTextPainter.h +++ b/src/common/RichTextPainter.h @@ -10,21 +10,18 @@ #include class QFontMetricsF; -template class CachedFontMetrics; +template +class CachedFontMetrics; class QPainter; class RichTextPainter { public: - //structures - enum CustomRichTextFlags { - FlagNone, - FlagColor, - FlagBackground, - FlagAll - }; + // structures + enum CustomRichTextFlags { FlagNone, FlagColor, FlagBackground, FlagAll }; - struct CustomRichText_t { + struct CustomRichText_t + { QString text; QColor textColor; QColor textBackground; @@ -37,10 +34,10 @@ public: typedef std::vector List; - //functions + // functions template - static void paintRichText(QPainter *painter, T x, T y, T w, T h, T xinc, - const List &richText, CachedFontMetrics *fontMetrics); + static void paintRichText(QPainter *painter, T x, T y, T w, T h, T xinc, const List &richText, + CachedFontMetrics *fontMetrics); static void htmlRichText(const List &richText, QString &textHtml, QString &textPlain); static List fromTextDocument(const QTextDocument &doc); diff --git a/src/common/RizinTask.cpp b/src/common/RizinTask.cpp index d48cfaf8..48cb0901 100644 --- a/src/common/RizinTask.cpp +++ b/src/common/RizinTask.cpp @@ -33,10 +33,9 @@ void RizinTask::taskFinished() RizinCmdTask::RizinCmdTask(const QString &cmd, bool transient) { - task = rz_core_cmd_task_new(Core()->core(), - cmd.toLocal8Bit().constData(), - static_cast(&RizinCmdTask::taskFinishedCallback), - this); + task = rz_core_cmd_task_new( + Core()->core(), cmd.toLocal8Bit().constData(), + static_cast(&RizinCmdTask::taskFinishedCallback), this); task->transient = transient; rz_core_task_incref(task); } @@ -74,9 +73,8 @@ const char *RizinCmdTask::getResultRaw() RizinFunctionTask::RizinFunctionTask(std::function fcn, bool transient) : fcn(fcn), res(nullptr) { - task = rz_core_function_task_new(Core()->core(), - static_cast(&RizinFunctionTask::runner), - this); + task = rz_core_function_task_new( + Core()->core(), static_cast(&RizinFunctionTask::runner), this); task->transient = transient; rz_core_task_incref(task); } diff --git a/src/common/RizinTask.h b/src/common/RizinTask.h index 84cbaf90..e07e1fb3 100644 --- a/src/common/RizinTask.h +++ b/src/common/RizinTask.h @@ -4,7 +4,7 @@ #include "core/Cutter.h" -class CUTTER_EXPORT RizinTask: public QObject +class CUTTER_EXPORT RizinTask : public QObject { Q_OBJECT @@ -27,7 +27,7 @@ signals: void finished(); }; -class CUTTER_EXPORT RizinCmdTask: public RizinTask +class CUTTER_EXPORT RizinCmdTask : public RizinTask { Q_OBJECT @@ -42,7 +42,7 @@ public: const char *getResultRaw(); }; -class CUTTER_EXPORT RizinFunctionTask: public RizinTask +class CUTTER_EXPORT RizinFunctionTask : public RizinTask { Q_OBJECT diff --git a/src/common/RunScriptTask.cpp b/src/common/RunScriptTask.cpp index cdeb6521..7bac2d99 100644 --- a/src/common/RunScriptTask.cpp +++ b/src/common/RunScriptTask.cpp @@ -2,14 +2,9 @@ #include "common/RunScriptTask.h" #include "core/MainWindow.h" -RunScriptTask::RunScriptTask() : - AsyncTask() -{ -} +RunScriptTask::RunScriptTask() : AsyncTask() {} -RunScriptTask::~RunScriptTask() -{ -} +RunScriptTask::~RunScriptTask() {} void RunScriptTask::interrupt() { diff --git a/src/common/RunScriptTask.h b/src/common/RunScriptTask.h index cfff047c..03c135bd 100644 --- a/src/common/RunScriptTask.h +++ b/src/common/RunScriptTask.h @@ -12,13 +12,9 @@ public: explicit RunScriptTask(); ~RunScriptTask(); - QString getTitle() override { - return tr("Run Script"); - } + QString getTitle() override { return tr("Run Script"); } - void setFileName(const QString &fileName) { - this->fileName = fileName; - } + void setFileName(const QString &fileName) { this->fileName = fileName; } void interrupt() override; diff --git a/src/common/SelectionHighlight.cpp b/src/common/SelectionHighlight.cpp index 94a2cf98..e7c2ee72 100644 --- a/src/common/SelectionHighlight.cpp +++ b/src/common/SelectionHighlight.cpp @@ -8,7 +8,8 @@ #include #include -QList createSameWordsSelections(QPlainTextEdit *textEdit, const QString &word) +QList createSameWordsSelections(QPlainTextEdit *textEdit, + const QString &word) { QList selections; QTextEdit::ExtraSelection highlightSelection; @@ -23,8 +24,8 @@ QList createSameWordsSelections(QPlainTextEdit *textE highlightSelection.cursor.movePosition(QTextCursor::Start, QTextCursor::MoveAnchor); while (!highlightSelection.cursor.isNull() && !highlightSelection.cursor.atEnd()) { - highlightSelection.cursor = document->find(word, highlightSelection.cursor, - QTextDocument::FindWholeWords); + highlightSelection.cursor = + document->find(word, highlightSelection.cursor, QTextDocument::FindWholeWords); if (!highlightSelection.cursor.isNull()) { highlightSelection.format.setBackground(highlightWordColor); @@ -35,7 +36,6 @@ QList createSameWordsSelections(QPlainTextEdit *textE return selections; } - QTextEdit::ExtraSelection createLineHighlight(const QTextCursor &cursor, QColor highlightColor) { QTextEdit::ExtraSelection highlightSelection; @@ -52,7 +52,6 @@ QTextEdit::ExtraSelection createLineHighlightSelection(const QTextCursor &cursor return createLineHighlight(cursor, highlightColor); } - QTextEdit::ExtraSelection createLineHighlightPC(const QTextCursor &cursor) { QColor highlightColor = ConfigColor("highlightPC"); diff --git a/src/common/SelectionHighlight.h b/src/common/SelectionHighlight.h index 7af33743..e85e3f10 100644 --- a/src/common/SelectionHighlight.h +++ b/src/common/SelectionHighlight.h @@ -12,25 +12,27 @@ class QString; * @param word * @return */ -QList createSameWordsSelections(QPlainTextEdit *textEdit, const QString &word); +QList createSameWordsSelections(QPlainTextEdit *textEdit, + const QString &word); /** * @brief createLineHighlight * @param cursor - a Cursor object represents the line to be highlighted - * @param highlightColor - the color to be used for highlighting. The color is decided by the callee for different usages (BP, PC, Current line, ...) + * @param highlightColor - the color to be used for highlighting. The color is decided by the callee + * for different usages (BP, PC, Current line, ...) * @return ExtraSelection with highlighted line */ QTextEdit::ExtraSelection createLineHighlight(const QTextCursor &cursor, QColor highlightColor); /** - * @brief This function responsible to highlight the currently selected line + * @brief This function responsible to highlight the currently selected line * @param cursor - a Cursor object represents the line to be highlighted * @return ExtraSelection with highlighted line */ QTextEdit::ExtraSelection createLineHighlightSelection(const QTextCursor &cursor); /** - * @brief This function responsible to highlight the program counter line + * @brief This function responsible to highlight the program counter line * @param cursor - a Cursor object represents the line to be highlighted * @return ExtraSelection with highlighted line */ @@ -43,4 +45,4 @@ QTextEdit::ExtraSelection createLineHighlightPC(const QTextCursor &cursor); */ QTextEdit::ExtraSelection createLineHighlightBP(const QTextCursor &cursor); -#endif //CUTTER_SELECTIONHIGHLIGHT_H +#endif // CUTTER_SELECTIONHIGHLIGHT_H diff --git a/src/common/SettingsUpgrade.cpp b/src/common/SettingsUpgrade.cpp index 8b4058aa..1f3563ea 100644 --- a/src/common/SettingsUpgrade.cpp +++ b/src/common/SettingsUpgrade.cpp @@ -9,7 +9,7 @@ */ static bool migrateSettingsPre18(QSettings &newSettings) { - if(newSettings.value("settings_migrated", false).toBool()) { + if (newSettings.value("settings_migrated", false).toBool()) { return false; } QSettings oldSettings(QSettings::NativeFormat, QSettings::Scope::UserScope, "Cutter", "Cutter"); @@ -29,7 +29,7 @@ static bool migrateSettingsPre18(QSettings &newSettings) } #define CUTTER_SETTINGS_VERSION_CURRENT 6 -#define CUTTER_SETTINGS_VERSION_KEY "version" +#define CUTTER_SETTINGS_VERSION_KEY "version" /* * How Settings migrations work: @@ -40,28 +40,30 @@ static bool migrateSettingsPre18(QSettings &newSettings) * This function takes care of migrating from EXACTLY version X-1 to X. */ -static void migrateSettingsTo1(QSettings &settings) { +static void migrateSettingsTo1(QSettings &settings) +{ settings.remove("settings_migrated"); // now handled by version settings.remove("updated_custom_themes"); // now handled by theme_version } -static void migrateSettingsTo2(QSettings &settings) { +static void migrateSettingsTo2(QSettings &settings) +{ QStringList docks = settings.value("docks").toStringList(); // get current list of docks // replace occurences of "PseudocodeWidget" with "DecompilerWidget" settings.setValue("docks", docks.replaceInStrings("PseudocodeWidget", "DecompilerWidget")); } -static void migrateSettingsTo3(QSettings &settings) { +static void migrateSettingsTo3(QSettings &settings) +{ auto defaultGeometry = settings.value("geometry").toByteArray(); auto defaultState = settings.value("state").toByteArray(); auto debugGeometry = settings.value("debug.geometry").toByteArray(); auto debugState = settings.value("debug.state").toByteArray(); - const auto docks = settings.value("docks", QStringList()).toStringList(); auto unsyncList = settings.value("unsync", QStringList()).toStringList(); -#if QT_VERSION < QT_VERSION_CHECK(5,14,0) +#if QT_VERSION < QT_VERSION_CHECK(5, 14, 0) QSet unsyncDocks = unsyncList.toSet(); #else QSet unsyncDocks(unsyncList.begin(), unsyncList.end()); @@ -105,11 +107,11 @@ static void migrateSettingsTo3(QSettings &settings) { static void renameAsmOption(QSettings &settings, const QString &oldName, const QString &newName) { - if (settings.contains(oldName)) { - auto value = settings.value(oldName); - settings.remove(oldName); - settings.setValue(newName, value); - } + if (settings.contains(oldName)) { + auto value = settings.value(oldName); + settings.remove(oldName); + settings.setValue(newName, value); + } } static void migrateSettingsTo4(QSettings &settings) @@ -134,29 +136,35 @@ void Cutter::initializeSettings() QSettings settings; int settingsVersion = settings.value(CUTTER_SETTINGS_VERSION_KEY, 0).toInt(); - if(settingsVersion == 0) { + if (settingsVersion == 0) { migrateSettingsPre18(settings); } - if(settings.allKeys().length() > 0) { + if (settings.allKeys().length() > 0) { if (settingsVersion > CUTTER_SETTINGS_VERSION_CURRENT) { qWarning() << "Settings have a higher version than current! Skipping migration."; - } else if(settingsVersion >= 0) { + } else if (settingsVersion >= 0) { for (int v = settingsVersion + 1; v <= CUTTER_SETTINGS_VERSION_CURRENT; v++) { qInfo() << "Migrating Settings to Version" << v; switch (v) { case 1: - migrateSettingsTo1(settings); break; + migrateSettingsTo1(settings); + break; case 2: - migrateSettingsTo2(settings); break; + migrateSettingsTo2(settings); + break; case 3: - migrateSettingsTo3(settings); break; + migrateSettingsTo3(settings); + break; case 4: - migrateSettingsTo4(settings); break; + migrateSettingsTo4(settings); + break; case 5: - migrateSettingsTo5(settings); break; + migrateSettingsTo5(settings); + break; case 6: - migrateSettingsTo6(settings); break; + migrateSettingsTo6(settings); + break; default: break; } @@ -166,12 +174,13 @@ void Cutter::initializeSettings() settings.setValue(CUTTER_SETTINGS_VERSION_KEY, CUTTER_SETTINGS_VERSION_CURRENT); } -#define THEME_VERSION_CURRENT 1 -#define THEME_VERSION_KEY "theme_version" +#define THEME_VERSION_CURRENT 1 +#define THEME_VERSION_KEY "theme_version" -static void removeObsoleteOptionsFromCustomThemes() { +static void removeObsoleteOptionsFromCustomThemes() +{ const QStringList options = Core()->cmdj("ecj").object().keys() - << ColorThemeWorker::cutterSpecificOptions; + << ColorThemeWorker::cutterSpecificOptions; for (auto theme : Core()->cmdList("eco*")) { theme = theme.trimmed(); if (!ThemeWorker().isCustomTheme(theme)) { @@ -179,7 +188,7 @@ static void removeObsoleteOptionsFromCustomThemes() { } QJsonObject updatedTheme; auto sch = ThemeWorker().getTheme(theme).object(); - for (const auto& key : sch.keys()) { + for (const auto &key : sch.keys()) { if (options.contains(key)) { updatedTheme.insert(key, sch[key]); } diff --git a/src/common/SettingsUpgrade.h b/src/common/SettingsUpgrade.h index 8d58f245..bd06c931 100644 --- a/src/common/SettingsUpgrade.h +++ b/src/common/SettingsUpgrade.h @@ -5,8 +5,8 @@ #include namespace Cutter { - void initializeSettings(); - void migrateThemes(); +void initializeSettings(); +void migrateThemes(); } #endif // COMMON_SETTINGS_UPGRADE_H diff --git a/src/common/StringsTask.h b/src/common/StringsTask.h index 0a4ded49..ff046206 100644 --- a/src/common/StringsTask.h +++ b/src/common/StringsTask.h @@ -7,10 +7,10 @@ class StringsTask : public AsyncTask { -Q_OBJECT + Q_OBJECT public: - QString getTitle() override { return tr("Searching for Strings"); } + QString getTitle() override { return tr("Searching for Strings"); } signals: void stringSearchFinished(const QList &strings); @@ -23,4 +23,4 @@ protected: } }; -#endif //STRINGSASYNCTASK_H +#endif // STRINGSASYNCTASK_H diff --git a/src/common/SvgIconEngine.cpp b/src/common/SvgIconEngine.cpp index f237eece..c11e94e9 100644 --- a/src/common/SvgIconEngine.cpp +++ b/src/common/SvgIconEngine.cpp @@ -14,7 +14,8 @@ SvgIconEngine::SvgIconEngine(const QString &filename) this->svgData = file.readAll(); } -SvgIconEngine::SvgIconEngine(const QString &filename, const QColor &tintColor) : SvgIconEngine(filename) +SvgIconEngine::SvgIconEngine(const QString &filename, const QColor &tintColor) + : SvgIconEngine(filename) { this->svgData = qhelpers::applyColorToSvg(svgData, tintColor); } diff --git a/src/common/SvgIconEngine.h b/src/common/SvgIconEngine.h index 76ecbe57..b8280866 100644 --- a/src/common/SvgIconEngine.h +++ b/src/common/SvgIconEngine.h @@ -5,7 +5,7 @@ #include #include -class SvgIconEngine: public QIconEngine +class SvgIconEngine : public QIconEngine { private: QByteArray svgData; @@ -19,7 +19,6 @@ public: void paint(QPainter *painter, const QRect &rect, QIcon::Mode mode, QIcon::State state) override; QIconEngine *clone() const override; QPixmap pixmap(const QSize &size, QIcon::Mode mode, QIcon::State state) override; - }; -#endif //SVGICONENGINE_H +#endif // SVGICONENGINE_H diff --git a/src/common/SyntaxHighlighter.cpp b/src/common/SyntaxHighlighter.cpp index e8bfc0cc..64a2038e 100644 --- a/src/common/SyntaxHighlighter.cpp +++ b/src/common/SyntaxHighlighter.cpp @@ -3,13 +3,15 @@ #ifdef CUTTER_ENABLE_KSYNTAXHIGHLIGHTING -#include "Configuration.h" +# include "Configuration.h" -#include +# include -SyntaxHighlighter::SyntaxHighlighter(QTextDocument *document) : KSyntaxHighlighting::SyntaxHighlighter(document) +SyntaxHighlighter::SyntaxHighlighter(QTextDocument *document) + : KSyntaxHighlighting::SyntaxHighlighter(document) { - connect(Config(), &Configuration::kSyntaxHighlightingThemeChanged, this, &SyntaxHighlighter::updateTheme); + connect(Config(), &Configuration::kSyntaxHighlightingThemeChanged, this, + &SyntaxHighlighter::updateTheme); updateTheme(); } @@ -21,38 +23,56 @@ void SyntaxHighlighter::updateTheme() #endif - FallbackSyntaxHighlighter::FallbackSyntaxHighlighter(QTextDocument *parent) - : QSyntaxHighlighter(parent) - , commentStartExpression("/\\*") - , commentEndExpression("\\*/") + : QSyntaxHighlighter(parent), commentStartExpression("/\\*"), commentEndExpression("\\*/") { HighlightingRule rule; QStringList keywordPatterns; - //C language keywords - keywordPatterns << "\\bauto\\b" << "\\bdouble\\b" << "\\bint\\b" - << "\\bstruct\\b" << "\\bbreak\\b" << "\\belse\\b" - << "\\blong\\b" << "\\switch\\b" << "\\bcase\\b" - << "\\benum\\b" << "\\bregister\\b" << "\\btypedef\\b" - << "\\bchar\\b" << "\\bextern\\b" << "\\breturn\\b" - << "\\bunion\\b" << "\\bconst\\b" << "\\bfloat\\b" - << "\\bshort\\b" << "\\bunsigned\\b" << "\\bcontinue\\b" - << "\\bfor\\b" << "\\bsigned\\b" << "\\bvoid\\b" - << "\\bdefault\\b" << "\\bgoto\\b" << "\\bsizeof\\b" - << "\\bvolatile\\b" << "\\bdo\\b" << "\\bif\\b" - << "\\static\\b" << "\\while\\b"; + // C language keywords + keywordPatterns << "\\bauto\\b" + << "\\bdouble\\b" + << "\\bint\\b" + << "\\bstruct\\b" + << "\\bbreak\\b" + << "\\belse\\b" + << "\\blong\\b" + << "\\switch\\b" + << "\\bcase\\b" + << "\\benum\\b" + << "\\bregister\\b" + << "\\btypedef\\b" + << "\\bchar\\b" + << "\\bextern\\b" + << "\\breturn\\b" + << "\\bunion\\b" + << "\\bconst\\b" + << "\\bfloat\\b" + << "\\bshort\\b" + << "\\bunsigned\\b" + << "\\bcontinue\\b" + << "\\bfor\\b" + << "\\bsigned\\b" + << "\\bvoid\\b" + << "\\bdefault\\b" + << "\\bgoto\\b" + << "\\bsizeof\\b" + << "\\bvolatile\\b" + << "\\bdo\\b" + << "\\bif\\b" + << "\\static\\b" + << "\\while\\b"; QTextCharFormat keywordFormat; keywordFormat.setForeground(QColor(80, 200, 215)); - for ( const auto &pattern : keywordPatterns ) { + for (const auto &pattern : keywordPatterns) { rule.pattern.setPattern(pattern); rule.format = keywordFormat; highlightingRules.append(rule); } - //Functions + // Functions rule.pattern.setPattern("\\b[A-Za-z0-9_]+(?=\\()"); rule.format.clearBackground(); rule.format.clearForeground(); @@ -60,14 +80,14 @@ FallbackSyntaxHighlighter::FallbackSyntaxHighlighter(QTextDocument *parent) rule.format.setForeground(Qt::darkCyan); highlightingRules.append(rule); - //single-line comment + // single-line comment rule.pattern.setPattern("//[^\n]*"); rule.format.clearBackground(); rule.format.clearForeground(); rule.format.setForeground(Qt::gray); highlightingRules.append(rule); - //quotation + // quotation rule.pattern.setPattern("\".*\""); rule.format.clearBackground(); rule.format.clearForeground(); @@ -79,7 +99,7 @@ FallbackSyntaxHighlighter::FallbackSyntaxHighlighter(QTextDocument *parent) void FallbackSyntaxHighlighter::highlightBlock(const QString &text) { - for ( const auto &it : highlightingRules ) { + for (const auto &it : highlightingRules) { auto matchIterator = it.pattern.globalMatch(text); while (matchIterator.hasNext()) { const auto match = matchIterator.next(); @@ -103,8 +123,7 @@ void FallbackSyntaxHighlighter::highlightBlock(const QString &text) setCurrentBlockState(1); commentLength = text.length() - startIndex; } else { - commentLength = endIndex - startIndex - + match.capturedLength(); + commentLength = endIndex - startIndex + match.capturedLength(); } setFormat(startIndex, commentLength, multiLineCommentFormat); diff --git a/src/common/SyntaxHighlighter.h b/src/common/SyntaxHighlighter.h index 80d6b845..b9e88970 100644 --- a/src/common/SyntaxHighlighter.h +++ b/src/common/SyntaxHighlighter.h @@ -10,7 +10,7 @@ #ifdef CUTTER_ENABLE_KSYNTAXHIGHLIGHTING -#include +# include class SyntaxHighlighter : public KSyntaxHighlighting::SyntaxHighlighter { @@ -40,7 +40,8 @@ protected: void highlightBlock(const QString &text) override; private: - struct HighlightingRule { + struct HighlightingRule + { QRegularExpression pattern; QTextCharFormat format; }; diff --git a/src/common/TempConfig.h b/src/common/TempConfig.h index 1fed343f..ba9b6f1e 100644 --- a/src/common/TempConfig.h +++ b/src/common/TempConfig.h @@ -10,10 +10,10 @@ /** * @brief Class for temporary modifying Rizin `e` configuration. * - * Modified values will be restored at the end of scope. This is useful when using a Rizin command that can only - * be configured using `e` configuration and doesn't accept arguments. TempConfig::set calls can be chained. - * If a command or Rizin method accepts arguments directly it is preferred to use those instead of temporary modifying - * global configuration. + * Modified values will be restored at the end of scope. This is useful when using a Rizin command + * that can only be configured using `e` configuration and doesn't accept arguments. TempConfig::set + * calls can be chained. If a command or Rizin method accepts arguments directly it is preferred to + * use those instead of temporary modifying global configuration. * * \code * { @@ -36,9 +36,9 @@ public: TempConfig &set(const QString &key, bool value); private: - TempConfig(const TempConfig&) = delete; - TempConfig &operator=(const TempConfig&) = delete; + TempConfig(const TempConfig &) = delete; + TempConfig &operator=(const TempConfig &) = delete; QMap resetValues; }; -#endif //TEMPCONFIG_H +#endif // TEMPCONFIG_H diff --git a/src/common/UpdateWorker.cpp b/src/common/UpdateWorker.cpp index a5667b11..0ee2c380 100644 --- a/src/common/UpdateWorker.cpp +++ b/src/common/UpdateWorker.cpp @@ -1,37 +1,37 @@ #include "UpdateWorker.h" #if CUTTER_UPDATE_WORKER_AVAILABLE -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include -#include -#include -#include -#include -#include "common/Configuration.h" -#include "CutterConfig.h" +# include +# include +# include +# include +# include "common/Configuration.h" +# include "CutterConfig.h" #endif #if CUTTER_UPDATE_WORKER_AVAILABLE -UpdateWorker::UpdateWorker(QObject *parent) : - QObject(parent), pending(false) +UpdateWorker::UpdateWorker(QObject *parent) : QObject(parent), pending(false) { connect(&t, &QTimer::timeout, this, [this]() { if (pending) { disconnect(checkReply, nullptr, this, nullptr); checkReply->close(); checkReply->deleteLater(); - emit checkComplete(QVersionNumber(), tr("Time limit exceeded during version check. Please check your " - "internet connection and try again.")); + emit checkComplete(QVersionNumber(), + tr("Time limit exceeded during version check. Please check your " + "internet connection and try again.")); } }); } @@ -47,8 +47,7 @@ void UpdateWorker::checkCurrentVersion(time_t timeoutMs) t.start(); checkReply = nm.get(request); - connect(checkReply, &QNetworkReply::finished, - this, &UpdateWorker::serveVersionCheckReply); + connect(checkReply, &QNetworkReply::finished, this, &UpdateWorker::serveVersionCheckReply); pending = true; } @@ -60,26 +59,27 @@ void UpdateWorker::download(QString filename, QString version) QNetworkRequest request; request.setAttribute(QNetworkRequest::FollowRedirectsAttribute, true); QUrl url(QString("https://github.com/rizinorg/cutter/releases/" - "download/v%1/%2").arg(version).arg(getRepositoryFileName())); + "download/v%1/%2") + .arg(version) + .arg(getRepositoryFileName())); request.setUrl(url); downloadReply = nm.get(request); - connect(downloadReply, &QNetworkReply::downloadProgress, - this, &UpdateWorker::process); - connect(downloadReply, &QNetworkReply::finished, - this, &UpdateWorker::serveDownloadFinish); + connect(downloadReply, &QNetworkReply::downloadProgress, this, &UpdateWorker::process); + connect(downloadReply, &QNetworkReply::finished, this, &UpdateWorker::serveDownloadFinish); } void UpdateWorker::showUpdateDialog(bool showDontCheckForUpdatesButton) { QMessageBox mb; mb.setWindowTitle(tr("Version control")); - mb.setText(tr("There is an update available for Cutter.
") - + "" + tr("Current version:") + " " CUTTER_VERSION_FULL "
" - + "" + tr("Latest version:") + " " + latestVersion.toString() + "

" + mb.setText(tr("There is an update available for Cutter.
") + "" + tr("Current version:") + + " " CUTTER_VERSION_FULL "
" + "" + tr("Latest version:") + " " + + latestVersion.toString() + "

" + tr("For update, please check the link:
") + QString("" - "https://github.com/rizinorg/cutter/releases/tag/v%1
").arg(latestVersion.toString()) + "https://github.com/rizinorg/cutter/releases/tag/v%1
") + .arg(latestVersion.toString()) + tr("or click \"Download\" to download latest version of Cutter.")); if (showDontCheckForUpdatesButton) { mb.setStandardButtons(QMessageBox::Save | QMessageBox::Reset | QMessageBox::Ok); @@ -93,31 +93,23 @@ void UpdateWorker::showUpdateDialog(bool showDontCheckForUpdatesButton) if (ret == QMessageBox::Reset) { Config()->setAutoUpdateEnabled(false); } else if (ret == QMessageBox::Save) { - QString fullFileName = - QFileDialog::getSaveFileName(nullptr, - tr("Choose directory for downloading"), - QStandardPaths::writableLocation(QStandardPaths::HomeLocation) + - QDir::separator() + getRepositoryFileName(), - QString("%1 (*.%1)").arg(getRepositeryExt())); + QString fullFileName = QFileDialog::getSaveFileName( + nullptr, tr("Choose directory for downloading"), + QStandardPaths::writableLocation(QStandardPaths::HomeLocation) + QDir::separator() + + getRepositoryFileName(), + QString("%1 (*.%1)").arg(getRepositeryExt())); if (!fullFileName.isEmpty()) { - QProgressDialog progressDial(tr("Downloading update..."), - tr("Cancel"), - 0, 100); + QProgressDialog progressDial(tr("Downloading update..."), tr("Cancel"), 0, 100); connect(this, &UpdateWorker::downloadProcess, &progressDial, [&progressDial](size_t curr, size_t total) { - progressDial.setValue(100.0f * curr / total); - }); - connect(&progressDial, &QProgressDialog::canceled, - this, &UpdateWorker::abortDownload); - connect(this, &UpdateWorker::downloadFinished, - &progressDial, &QProgressDialog::cancel); - connect(this, &UpdateWorker::downloadFinished, this, - [](QString filePath){ - QMessageBox info(QMessageBox::Information, - tr("Download finished!"), + progressDial.setValue(100.0f * curr / total); + }); + connect(&progressDial, &QProgressDialog::canceled, this, &UpdateWorker::abortDownload); + connect(this, &UpdateWorker::downloadFinished, &progressDial, &QProgressDialog::cancel); + connect(this, &UpdateWorker::downloadFinished, this, [](QString filePath) { + QMessageBox info(QMessageBox::Information, tr("Download finished!"), tr("Latest version of Cutter was succesfully downloaded!"), - QMessageBox::Yes | QMessageBox::Open | QMessageBox::Ok, - nullptr); + QMessageBox::Yes | QMessageBox::Open | QMessageBox::Ok, nullptr); info.button(QMessageBox::Open)->setText(tr("Open file")); info.button(QMessageBox::Yes)->setText(tr("Open download folder")); int r = info.exec(); @@ -140,10 +132,8 @@ void UpdateWorker::showUpdateDialog(bool showDontCheckForUpdatesButton) void UpdateWorker::abortDownload() { - disconnect(downloadReply, &QNetworkReply::finished, - this, &UpdateWorker::serveDownloadFinish); - disconnect(downloadReply, &QNetworkReply::downloadProgress, - this, &UpdateWorker::process); + disconnect(downloadReply, &QNetworkReply::finished, this, &UpdateWorker::serveDownloadFinish); + disconnect(downloadReply, &QNetworkReply::downloadProgress, this, &UpdateWorker::process); downloadReply->close(); downloadReply->deleteLater(); downloadFile.remove(); @@ -157,7 +147,10 @@ void UpdateWorker::serveVersionCheckReply() if (checkReply->error()) { errStr = checkReply->errorString(); } else { - versionReplyStr = QJsonDocument::fromJson(checkReply->readAll()).object().value("tag_name").toString(); + versionReplyStr = QJsonDocument::fromJson(checkReply->readAll()) + .object() + .value("tag_name") + .toString(); versionReplyStr.remove('v'); } QVersionNumber versionReply = QVersionNumber::fromString(versionReplyStr); @@ -188,30 +181,28 @@ void UpdateWorker::process(size_t bytesReceived, size_t bytesTotal) QString UpdateWorker::getRepositeryExt() const { -#ifdef Q_OS_LINUX +# ifdef Q_OS_LINUX return "AppImage"; -#elif defined (Q_OS_WIN64) || defined (Q_OS_WIN32) +# elif defined(Q_OS_WIN64) || defined(Q_OS_WIN32) return "zip"; -#elif defined (Q_OS_MACOS) +# elif defined(Q_OS_MACOS) return "dmg"; -#endif +# endif } QString UpdateWorker::getRepositoryFileName() const { QString downloadFileName; -#ifdef Q_OS_LINUX +# ifdef Q_OS_LINUX downloadFileName = "Cutter-v%1-x%2.Linux.AppImage"; -#elif defined (Q_OS_WIN64) || defined (Q_OS_WIN32) +# elif defined(Q_OS_WIN64) || defined(Q_OS_WIN32) downloadFileName = "Cutter-v%1-x%2.Windows.zip"; -#elif defined (Q_OS_MACOS) +# elif defined(Q_OS_MACOS) downloadFileName = "Cutter-v%1-x%2.macOS.dmg"; -#endif - downloadFileName = downloadFileName - .arg(latestVersion.toString()) - .arg(QSysInfo::buildAbi().split('-').at(2).contains("64") - ? "64" - : "32"); +# endif + downloadFileName = + downloadFileName.arg(latestVersion.toString()) + .arg(QSysInfo::buildAbi().split('-').at(2).contains("64") ? "64" : "32"); return downloadFileName; } diff --git a/src/common/UpdateWorker.h b/src/common/UpdateWorker.h index 225299e6..61b8d038 100644 --- a/src/common/UpdateWorker.h +++ b/src/common/UpdateWorker.h @@ -4,18 +4,18 @@ #include #if (QT_VERSION >= QT_VERSION_CHECK(5, 6, 0)) -#define CUTTER_UPDATE_WORKER_AVAILABLE 1 +# define CUTTER_UPDATE_WORKER_AVAILABLE 1 #else -#define CUTTER_UPDATE_WORKER_AVAILABLE 0 +# define CUTTER_UPDATE_WORKER_AVAILABLE 0 #endif #if CUTTER_UPDATE_WORKER_AVAILABLE -#include -#include -#include -#include +# include +# include +# include +# include -#include +# include #endif #if CUTTER_UPDATE_WORKER_AVAILABLE @@ -68,7 +68,8 @@ public: void showUpdateDialog(bool showDontCheckForUpdatesButton); /** - * @return the version of this Cutter binary, derived from CUTTER_VERSION_MAJOR, CUTTER_VERSION_MINOR and CUTTER_VERSION_PATCH. + * @return the version of this Cutter binary, derived from CUTTER_VERSION_MAJOR, + * CUTTER_VERSION_MINOR and CUTTER_VERSION_PATCH. */ static QVersionNumber currentVersionNumber(); @@ -102,7 +103,6 @@ signals: */ void downloadProcess(size_t bytesReceived, size_t bytesTotal); - /** * @fn UpdateWorker::downloadFinished(QString filename) * @@ -138,5 +138,5 @@ private: QNetworkReply *checkReply; }; -#endif //CUTTER_UPDATE_WORKER_AVAILABLE +#endif // CUTTER_UPDATE_WORKER_AVAILABLE #endif // UPDATEWORKER_H diff --git a/src/core/Cutter.cpp b/src/core/Cutter.cpp index 96e751d0..b1018047 100644 --- a/src/core/Cutter.cpp +++ b/src/core/Cutter.cpp @@ -29,86 +29,86 @@ Q_GLOBAL_STATIC(CutterCore, uniqueInstance) #define RZ_JSON_KEY(name) static const QString name = QStringLiteral(#name) namespace RJsonKey { - RZ_JSON_KEY(addr); - RZ_JSON_KEY(addrs); - RZ_JSON_KEY(addr_end); - RZ_JSON_KEY(arrow); - RZ_JSON_KEY(baddr); - RZ_JSON_KEY(bind); - RZ_JSON_KEY(blocks); - RZ_JSON_KEY(blocksize); - RZ_JSON_KEY(bytes); - RZ_JSON_KEY(calltype); - RZ_JSON_KEY(cc); - RZ_JSON_KEY(classname); - RZ_JSON_KEY(code); - RZ_JSON_KEY(comment); - RZ_JSON_KEY(comments); - RZ_JSON_KEY(cost); - RZ_JSON_KEY(data); - RZ_JSON_KEY(description); - RZ_JSON_KEY(ebbs); - RZ_JSON_KEY(edges); - RZ_JSON_KEY(enabled); - RZ_JSON_KEY(entropy); - RZ_JSON_KEY(fcn_addr); - RZ_JSON_KEY(fcn_name); - RZ_JSON_KEY(fields); - RZ_JSON_KEY(file); - RZ_JSON_KEY(flags); - RZ_JSON_KEY(flagname); - RZ_JSON_KEY(format); - RZ_JSON_KEY(from); - RZ_JSON_KEY(functions); - RZ_JSON_KEY(graph); - RZ_JSON_KEY(haddr); - RZ_JSON_KEY(hw); - RZ_JSON_KEY(in_functions); - RZ_JSON_KEY(index); - RZ_JSON_KEY(jump); - RZ_JSON_KEY(laddr); - RZ_JSON_KEY(lang); - RZ_JSON_KEY(len); - RZ_JSON_KEY(length); - RZ_JSON_KEY(license); - RZ_JSON_KEY(methods); - RZ_JSON_KEY(name); - RZ_JSON_KEY(realname); - RZ_JSON_KEY(nargs); - RZ_JSON_KEY(nbbs); - RZ_JSON_KEY(nlocals); - RZ_JSON_KEY(offset); - RZ_JSON_KEY(opcode); - RZ_JSON_KEY(opcodes); - RZ_JSON_KEY(ordinal); - RZ_JSON_KEY(libname); - RZ_JSON_KEY(outdegree); - RZ_JSON_KEY(paddr); - RZ_JSON_KEY(path); - RZ_JSON_KEY(perm); - RZ_JSON_KEY(pid); - RZ_JSON_KEY(plt); - RZ_JSON_KEY(prot); - RZ_JSON_KEY(ref); - RZ_JSON_KEY(refs); - RZ_JSON_KEY(reg); - RZ_JSON_KEY(rwx); - RZ_JSON_KEY(section); - RZ_JSON_KEY(sections); - RZ_JSON_KEY(size); - RZ_JSON_KEY(stackframe); - RZ_JSON_KEY(status); - RZ_JSON_KEY(string); - RZ_JSON_KEY(strings); - RZ_JSON_KEY(symbols); - RZ_JSON_KEY(text); - RZ_JSON_KEY(to); - RZ_JSON_KEY(trace); - RZ_JSON_KEY(type); - RZ_JSON_KEY(uid); - RZ_JSON_KEY(vaddr); - RZ_JSON_KEY(value); - RZ_JSON_KEY(vsize); +RZ_JSON_KEY(addr); +RZ_JSON_KEY(addrs); +RZ_JSON_KEY(addr_end); +RZ_JSON_KEY(arrow); +RZ_JSON_KEY(baddr); +RZ_JSON_KEY(bind); +RZ_JSON_KEY(blocks); +RZ_JSON_KEY(blocksize); +RZ_JSON_KEY(bytes); +RZ_JSON_KEY(calltype); +RZ_JSON_KEY(cc); +RZ_JSON_KEY(classname); +RZ_JSON_KEY(code); +RZ_JSON_KEY(comment); +RZ_JSON_KEY(comments); +RZ_JSON_KEY(cost); +RZ_JSON_KEY(data); +RZ_JSON_KEY(description); +RZ_JSON_KEY(ebbs); +RZ_JSON_KEY(edges); +RZ_JSON_KEY(enabled); +RZ_JSON_KEY(entropy); +RZ_JSON_KEY(fcn_addr); +RZ_JSON_KEY(fcn_name); +RZ_JSON_KEY(fields); +RZ_JSON_KEY(file); +RZ_JSON_KEY(flags); +RZ_JSON_KEY(flagname); +RZ_JSON_KEY(format); +RZ_JSON_KEY(from); +RZ_JSON_KEY(functions); +RZ_JSON_KEY(graph); +RZ_JSON_KEY(haddr); +RZ_JSON_KEY(hw); +RZ_JSON_KEY(in_functions); +RZ_JSON_KEY(index); +RZ_JSON_KEY(jump); +RZ_JSON_KEY(laddr); +RZ_JSON_KEY(lang); +RZ_JSON_KEY(len); +RZ_JSON_KEY(length); +RZ_JSON_KEY(license); +RZ_JSON_KEY(methods); +RZ_JSON_KEY(name); +RZ_JSON_KEY(realname); +RZ_JSON_KEY(nargs); +RZ_JSON_KEY(nbbs); +RZ_JSON_KEY(nlocals); +RZ_JSON_KEY(offset); +RZ_JSON_KEY(opcode); +RZ_JSON_KEY(opcodes); +RZ_JSON_KEY(ordinal); +RZ_JSON_KEY(libname); +RZ_JSON_KEY(outdegree); +RZ_JSON_KEY(paddr); +RZ_JSON_KEY(path); +RZ_JSON_KEY(perm); +RZ_JSON_KEY(pid); +RZ_JSON_KEY(plt); +RZ_JSON_KEY(prot); +RZ_JSON_KEY(ref); +RZ_JSON_KEY(refs); +RZ_JSON_KEY(reg); +RZ_JSON_KEY(rwx); +RZ_JSON_KEY(section); +RZ_JSON_KEY(sections); +RZ_JSON_KEY(size); +RZ_JSON_KEY(stackframe); +RZ_JSON_KEY(status); +RZ_JSON_KEY(string); +RZ_JSON_KEY(strings); +RZ_JSON_KEY(symbols); +RZ_JSON_KEY(text); +RZ_JSON_KEY(to); +RZ_JSON_KEY(trace); +RZ_JSON_KEY(type); +RZ_JSON_KEY(uid); +RZ_JSON_KEY(vaddr); +RZ_JSON_KEY(value); +RZ_JSON_KEY(vsize); } #undef RZ_JSON_KEY @@ -120,14 +120,14 @@ static void updateOwnedCharPtr(char *&variable, const QString &newValue) variable = strdup(data.data()); } -static QString fromOwnedCharPtr(char *str) { +static QString fromOwnedCharPtr(char *str) +{ QString result(str ? str : ""); rz_mem_free(str); return result; } -RzCoreLocked::RzCoreLocked(CutterCore *core) - : core(core) +RzCoreLocked::RzCoreLocked(CutterCore *core) : core(core) { core->coreMutex.lock(); assert(core->coreLockDepth >= 0); @@ -167,10 +167,11 @@ static void cutterREventCallback(RzEvent *, int type, void *user, void *data) core->handleREvent(type, data); } -CutterCore::CutterCore(QObject *parent): - QObject(parent) +CutterCore::CutterCore(QObject *parent) + : QObject(parent) #if QT_VERSION < QT_VERSION_CHECK(5, 14, 0) - , coreMutex(QMutex::Recursive) + , + coreMutex(QMutex::Recursive) #endif { } @@ -182,7 +183,7 @@ CutterCore *CutterCore::instance() void CutterCore::initialize(bool loadPlugins) { - rz_cons_new(); // initialize console + rz_cons_new(); // initialize console core_ = rz_core_new(); rz_core_task_sync_begin(&core_->tasks); coreBed = rz_cons_sleep_begin(); @@ -192,16 +193,17 @@ void CutterCore::initialize(bool loadPlugins) #if defined(APPIMAGE) || defined(MACOS_RZ_BUNDLED) auto prefix = QDir(QCoreApplication::applicationDirPath()); -#ifdef APPIMAGE +# ifdef APPIMAGE // Executable is in appdir/bin prefix.cdUp(); qInfo() << "Setting Rizin prefix =" << prefix.absolutePath() << " for AppImage."; -#else // MACOS_RZ_BUNDLED +# else // MACOS_RZ_BUNDLED // Executable is in Contents/MacOS, prefix is Contents/Resources/rz prefix.cdUp(); prefix.cd("Resources"); - qInfo() << "Setting Rizin prefix =" << prefix.absolutePath() << " for macOS Application Bundle."; -#endif + qInfo() << "Setting Rizin prefix =" << prefix.absolutePath() + << " for macOS Application Bundle."; +# endif setConfig("dir.prefix", prefix.absolutePath()); auto pluginsDir = prefix; @@ -255,10 +257,11 @@ QVector CutterCore::getCutterRCFilePaths() const QVector result; result.push_back(QFileInfo(QDir::home(), ".cutterrc").absoluteFilePath()); QStringList locations = QStandardPaths::standardLocations(QStandardPaths::AppConfigLocation); - for (auto &location : locations) { + for (auto &location : locations) { result.push_back(QFileInfo(QDir(location), ".cutterrc").absoluteFilePath()); } - result.push_back(QFileInfo(getCutterRCDefaultDirectory(), "rc").absoluteFilePath()); // File in config editor is from this path + result.push_back(QFileInfo(getCutterRCDefaultDirectory(), "rc") + .absoluteFilePath()); // File in config editor is from this path return result; } @@ -266,7 +269,7 @@ void CutterCore::loadCutterRC() { CORE_LOCK(); const auto result = getCutterRCFilePaths(); - for(auto &cutterRCFilePath : result){ + for (auto &cutterRCFilePath : result) { auto cutterRCFileInfo = QFileInfo(cutterRCFilePath); if (!cutterRCFileInfo.exists() || !cutterRCFileInfo.isFile()) { continue; @@ -288,7 +291,6 @@ void CutterCore::loadDefaultCutterRC() rz_core_cmd_file(core, cutterRCFilePath.toUtf8().constData()); } - QList CutterCore::sdbList(QString path) { CORE_LOCK(); @@ -297,7 +299,8 @@ QList CutterCore::sdbList(QString path) if (root) { void *vsi; ls_iter_t *iter; - ls_foreach(root->ns, iter, vsi) { + ls_foreach(root->ns, iter, vsi) + { SdbNs *nsi = (SdbNs *)vsi; list << nsi->name; } @@ -305,10 +308,10 @@ QList CutterCore::sdbList(QString path) return list; } -using SdbListPtr = std::unique_ptr; +using SdbListPtr = std::unique_ptr; static SdbListPtr makeSdbListPtr(SdbList *list) { - return {list, ls_free}; + return { list, ls_free }; } QList CutterCore::sdbListKeys(QString path) @@ -320,7 +323,8 @@ QList CutterCore::sdbListKeys(QString path) void *vsi; ls_iter_t *iter; SdbListPtr l = makeSdbListPtr(sdb_foreach_list(root, false)); - ls_foreach(l, iter, vsi) { + ls_foreach(l, iter, vsi) + { SdbKv *nsi = (SdbKv *)vsi; list << reinterpret_cast(nsi->base.key); } @@ -344,7 +348,8 @@ bool CutterCore::sdbSet(QString path, QString key, QString val) { CORE_LOCK(); Sdb *db = sdb_ns_path(core->sdb, path.toUtf8().constData(), 1); - if (!db) return false; + if (!db) + return false; return sdb_set(db, key.toUtf8().constData(), val.toUtf8().constData(), 0); } @@ -375,7 +380,8 @@ bool CutterCore::isRedirectableDebugee() } // We are only able to redirect locally debugged unix processes - QJsonArray openFilesArray = cmdj("oj").array();; + QJsonArray openFilesArray = cmdj("oj").array(); + ; for (QJsonValue value : openFilesArray) { QJsonObject openFile = value.toObject(); QString URI = openFile["uri"].toString(); @@ -403,11 +409,12 @@ bool CutterCore::asyncCmdEsil(const char *command, QSharedPointer return false; } - connect(task.data(), &RizinCmdTask::finished, task.data(), [this, task] () { + connect(task.data(), &RizinCmdTask::finished, task.data(), [this, task]() { QString res = task.data()->getResult(); if (res.contains(QStringLiteral("[ESIL] Stopped execution in an invalid instruction"))) { - msgBox.showMessage("Stopped when attempted to run an invalid instruction. You can disable this in Preferences"); + msgBox.showMessage("Stopped when attempted to run an invalid instruction. You can " + "disable this in Preferences"); } }); @@ -425,7 +432,7 @@ bool CutterCore::asyncCmd(const char *str, QSharedPointer &task) RVA offset = core->offset; task = QSharedPointer(new RizinCmdTask(str, true)); - connect(task.data(), &RizinCmdTask::finished, task.data(), [this, offset, task] () { + connect(task.data(), &RizinCmdTask::finished, task.data(), [this, offset, task]() { CORE_LOCK(); if (offset != core->offset) { @@ -452,7 +459,7 @@ QString CutterCore::cmdRaw(const char *cmd) { QString res; CORE_LOCK(); - rz_cons_push (); + rz_cons_push(); // rz_cmd_call does not return the output of the command rz_cmd_call(core->rcmd, cmd); @@ -461,9 +468,9 @@ QString CutterCore::cmdRaw(const char *cmd) res = rz_cons_get_buffer(); // cleaning up - rz_cons_pop (); - rz_cons_echo (NULL); - + rz_cons_pop(); + rz_cons_echo(NULL); + return res; } @@ -529,7 +536,8 @@ QJsonDocument CutterCore::parseJson(const char *res, const char *cmd) eprintf("Failed to parse JSON for command \"%s\": %s\n", cmd, jsonError.errorString().toLocal8Bit().constData()); } else { - eprintf("Failed to parse JSON: %s\n", jsonError.errorString().toLocal8Bit().constData()); + eprintf("Failed to parse JSON: %s\n", + jsonError.errorString().toLocal8Bit().constData()); } const int MAX_JSON_DUMP_SIZE = 8 * 1024; if (json.length() > MAX_JSON_DUMP_SIZE) { @@ -560,7 +568,8 @@ QStringList CutterCore::autocomplete(const QString &cmd, RzLinePromptType prompt QStringList r; r.reserve(rz_pvector_len(&completion.args)); for (size_t i = 0; i < rz_pvector_len(&completion.args); i++) { - r.push_back(QString::fromUtf8(reinterpret_cast(rz_pvector_at(&completion.args, i)))); + r.push_back(QString::fromUtf8( + reinterpret_cast(rz_pvector_at(&completion.args, i)))); } rz_line_completion_fini(&completion); @@ -579,8 +588,8 @@ QStringList CutterCore::autocomplete(const QString &cmd, RzLinePromptType prompt * @param forceBinPlugin * @return */ -bool CutterCore::loadFile(QString path, ut64 baddr, ut64 mapaddr, int perms, int va, - bool loadbin, const QString &forceBinPlugin) +bool CutterCore::loadFile(QString path, ut64 baddr, ut64 mapaddr, int perms, int va, bool loadbin, + const QString &forceBinPlugin) { CORE_LOCK(); RzCoreFile *f; @@ -616,15 +625,15 @@ bool CutterCore::loadFile(QString path, ut64 baddr, ut64 mapaddr, int perms, int } auto iod = core->io ? core->io->desc : NULL; - auto debug = core->file && iod && (core->file->fd == iod->fd) && iod->plugin && \ - iod->plugin->isdbg; + auto debug = + core->file && iod && (core->file->fd == iod->fd) && iod->plugin && iod->plugin->isdbg; - if (!debug && rz_flag_get (core->flags, "entry0")) { - rz_core_cmd0 (core, "s entry0"); + if (!debug && rz_flag_get(core->flags, "entry0")) { + rz_core_cmd0(core, "s entry0"); } if (perms & RZ_PERM_W) { - rz_core_cmd0 (core, "omfg+w"); + rz_core_cmd0(core, "omfg+w"); } fflush(stdout); @@ -636,13 +645,14 @@ bool CutterCore::tryFile(QString path, bool rw) CORE_LOCK(); RzCoreFile *cf; int flags = RZ_PERM_R; - if (rw) flags = RZ_PERM_RW; + if (rw) + flags = RZ_PERM_RW; cf = rz_core_file_open(core, path.toUtf8().constData(), flags, 0LL); if (!cf) { return false; } - rz_core_file_close (core, cf); + rz_core_file_close(core, cf); return true; } @@ -657,7 +667,8 @@ bool CutterCore::mapFile(QString path, RVA mapaddr) { CORE_LOCK(); RVA addr = mapaddr != RVA_INVALID ? mapaddr : 0; - ut64 baddr = Core()->getFileInfo().object()["bin"].toObject()["baddr"].toVariant().toULongLong(); + ut64 baddr = + Core()->getFileInfo().object()["bin"].toObject()["baddr"].toVariant().toULongLong(); if (rz_core_file_open(core, path.toUtf8().constData(), RZ_PERM_RX, addr)) { rz_core_bin_load(core, path.toUtf8().constData(), baddr); } else { @@ -688,7 +699,8 @@ void CutterCore::renameFunctionVariable(QString newName, QString oldName, RVA fu { CORE_LOCK(); RzAnalysisFunction *function = rz_analysis_get_function_at(core->analysis, functionAddress); - RzAnalysisVar *variable = rz_analysis_function_get_var_byname(function, oldName.toUtf8().constData()); + RzAnalysisVar *variable = + rz_analysis_function_get_var_byname(function, oldName.toUtf8().constData()); if (variable) { rz_analysis_var_rename(variable, newName.toUtf8().constData(), true); } @@ -709,12 +721,20 @@ void CutterCore::delFlag(const QString &name) QString CutterCore::getInstructionBytes(RVA addr) { - return cmdj("aoj @ " + RAddressString(addr)).array().first().toObject()[RJsonKey::bytes].toString(); + return cmdj("aoj @ " + RAddressString(addr)) + .array() + .first() + .toObject()[RJsonKey::bytes] + .toString(); } QString CutterCore::getInstructionOpcode(RVA addr) { - return cmdj("aoj @ " + RAddressString(addr)).array().first().toObject()[RJsonKey::opcode].toString(); + return cmdj("aoj @ " + RAddressString(addr)) + .array() + .first() + .toObject()[RJsonKey::opcode] + .toString(); } void CutterCore::editInstruction(RVA addr, const QString &inst) @@ -755,27 +775,22 @@ void CutterCore::setToCode(RVA addr) void CutterCore::setAsString(RVA addr, int size, StringTypeFormats type) { - if(RVA_INVALID == addr) - { + if (RVA_INVALID == addr) { return; } QString command; - switch(type) - { - case StringTypeFormats::None: - { + switch (type) { + case StringTypeFormats::None: { command = "Cs"; break; } - case StringTypeFormats::ASCII_LATIN1: - { + case StringTypeFormats::ASCII_LATIN1: { command = "Csa"; break; } - case StringTypeFormats::UTF8: - { + case StringTypeFormats::UTF8: { command = "Cs8"; break; } @@ -950,8 +965,9 @@ RVA CutterCore::nextOpAddr(RVA startAddr, int count) { CORE_LOCK(); - QJsonArray array = Core()->cmdj("pdj " + QString::number(count + 1) + "@" + QString::number( - startAddr)).array(); + QJsonArray array = + Core()->cmdj("pdj " + QString::number(count + 1) + "@" + QString::number(startAddr)) + .array(); if (array.isEmpty()) { return startAddr + 1; } @@ -1043,7 +1059,7 @@ bool CutterCore::getConfigb(const char *k) QString CutterCore::getConfigDescription(const char *k) { CORE_LOCK(); - RzConfigNode *node = rz_config_node_get (core->config, k); + RzConfigNode *node = rz_config_node_get(core->config, k); return node ? QString(node->desc) : QString("Unrecognized configuration key"); } @@ -1126,7 +1142,8 @@ QByteArray CutterCore::assemble(const QString &code) QString CutterCore::disassemble(const QByteArray &data) { CORE_LOCK(); - RzAsmCode *ac = rz_asm_mdisassemble(core->rasm, reinterpret_cast(data.constData()), data.length()); + RzAsmCode *ac = rz_asm_mdisassemble(core->rasm, reinterpret_cast(data.constData()), + data.length()); QString code; if (ac && ac->assembly) { code = QString::fromUtf8(ac->assembly); @@ -1143,8 +1160,10 @@ QString CutterCore::disassembleSingleInstruction(RVA addr) RzAnalysisFunction *CutterCore::functionIn(ut64 addr) { CORE_LOCK(); - RzList *fcns = rz_analysis_get_functions_in (core->analysis, addr); - RzAnalysisFunction *fcn = !rz_list_empty(fcns) ? reinterpret_cast(rz_list_first(fcns)) : nullptr; + RzList *fcns = rz_analysis_get_functions_in(core->analysis, addr); + RzAnalysisFunction *fcn = !rz_list_empty(fcns) + ? reinterpret_cast(rz_list_first(fcns)) + : nullptr; rz_list_free(fcns); return fcn; } @@ -1182,7 +1201,8 @@ RVA CutterCore::getFunctionEnd(RVA addr) /** * @brief finds the last instruction of a function in a given address * @param addr - an address which belongs to a function - * @returns if function exists, return the address of its last instruction. Otherwise return RVA_INVALID + * @returns if function exists, return the address of its last instruction. Otherwise return + * RVA_INVALID */ RVA CutterCore::getLastFunctionInstruction(RVA addr) { @@ -1192,7 +1212,7 @@ RVA CutterCore::getLastFunctionInstruction(RVA addr) return RVA_INVALID; } RzAnalysisBlock *lastBB = (RzAnalysisBlock *)rz_list_last(fcn->bbs); - return lastBB ? rz_analysis_block_get_op_addr(lastBB, lastBB->ninstr-1) : RVA_INVALID; + return lastBB ? rz_analysis_block_get_op_addr(lastBB, lastBB->ninstr - 1) : RVA_INVALID; } QString CutterCore::cmdFunctionAt(QString addr) @@ -1213,7 +1233,8 @@ void CutterCore::cmdEsil(const char *command) // use cmd and not cmdRaw because of unexpected commands QString res = cmd(command); if (res.contains(QStringLiteral("[ESIL] Stopped execution in an invalid instruction"))) { - msgBox.showMessage("Stopped when attempted to run an invalid instruction. You can disable this in Preferences"); + msgBox.showMessage("Stopped when attempted to run an invalid instruction. You can disable " + "this in Preferences"); } } @@ -1241,8 +1262,13 @@ QJsonDocument CutterCore::getRegistersInfo() RVA CutterCore::getOffsetJump(RVA addr) { bool ok; - RVA value = cmdj("aoj @" + QString::number( - addr)).array().first().toObject().value(RJsonKey::jump).toVariant().toULongLong(&ok); + RVA value = cmdj("aoj @" + QString::number(addr)) + .array() + .first() + .toObject() + .value(RJsonKey::jump) + .toVariant() + .toULongLong(&ok); if (!ok) { return RVA_INVALID; @@ -1251,7 +1277,6 @@ RVA CutterCore::getOffsetJump(RVA addr) return value; } - QList CutterCore::getDecompilers() { return decompilers; @@ -1294,7 +1319,7 @@ QJsonDocument CutterCore::getSignatureInfo() // Utility function to check if a telescoped item exists and add it with prefixes to the desc static inline const QString appendVar(QString &dst, const QString val, const QString prepend_val, - const QString append_val) + const QString append_val) { if (!val.isEmpty()) { dst += prepend_val + val + append_val; @@ -1332,7 +1357,8 @@ RefDescription CutterCore::formatRefDesc(QJsonObject refItem) break; } if (!refItem["value"].isNull()) { - appendVar(desc.ref, RAddressString(refItem["value"].toVariant().toULongLong()), " ", ""); + appendVar(desc.ref, RAddressString(refItem["value"].toVariant().toULongLong()), " ", + ""); } refItem = refItem["ref"].toObject(); } while (!refItem.empty()); @@ -1398,7 +1424,8 @@ QList CutterCore::getStack(int size, int depth) return stack; } -QJsonObject CutterCore::getAddrRefs(RVA addr, int depth) { +QJsonObject CutterCore::getAddrRefs(RVA addr, int depth) +{ QJsonObject json; if (depth < 1 || addr == UT64_MAX) { return json; @@ -1412,14 +1439,14 @@ QJsonObject CutterCore::getAddrRefs(RVA addr, int depth) { json["addr"] = QString::number(addr); // Search for the section the addr is in, avoid duplication for heap/stack with type - if(!(type & RZ_ANALYSIS_ADDR_TYPE_HEAP || type & RZ_ANALYSIS_ADDR_TYPE_STACK)) { + if (!(type & RZ_ANALYSIS_ADDR_TYPE_HEAP || type & RZ_ANALYSIS_ADDR_TYPE_STACK)) { // Attempt to find the address within a map RzDebugMap *map = rz_debug_map_get(core->dbg, addr); if (map && map->name && map->name[0]) { json["mapname"] = map->name; } - RzBinSection *sect = rz_bin_get_section_at(rz_bin_cur_object (core->bin), addr, true); + RzBinSection *sect = rz_bin_get_section_at(rz_bin_cur_object(core->bin), addr, true); if (sect && sect->name[0]) { json["section"] = sect->name; } @@ -1468,9 +1495,9 @@ QJsonObject CutterCore::getAddrRefs(RVA addr, int depth) { buf.resize(32); perms += "x"; // Instruction disassembly - rz_io_read_at(core->io, addr, (unsigned char*)buf.data(), buf.size()); + rz_io_read_at(core->io, addr, (unsigned char *)buf.data(), buf.size()); rz_asm_set_pc(core->rasm, addr); - rz_asm_disassemble(core->rasm, &op, (unsigned char*)buf.data(), buf.size()); + rz_asm_disassemble(core->rasm, &op, (unsigned char *)buf.data(), buf.size()); json["asm"] = rz_asm_op_get_asm(&op); } @@ -1484,8 +1511,8 @@ QJsonObject CutterCore::getAddrRefs(RVA addr, int depth) { buf.resize(64); ut32 *n32 = (ut32 *)buf.data(); ut64 *n64 = (ut64 *)buf.data(); - rz_io_read_at(core->io, addr, (unsigned char*)buf.data(), buf.size()); - ut64 n = (bits == 64)? *n64: *n32; + rz_io_read_at(core->io, addr, (unsigned char *)buf.data(), buf.size()); + ut64 n = (bits == 64) ? *n64 : *n32; // The value of the next address will serve as an indication that there's more to // telescope if we have reached the depth limit json["value"] = QString::number(n); @@ -1497,7 +1524,7 @@ QJsonObject CutterCore::getAddrRefs(RVA addr, int depth) { // might have a string in this address if (ref["type"].toString().contains("ascii")) { buf.resize(128); - rz_io_read_at(core->io, addr, (unsigned char*)buf.data(), buf.size()); + rz_io_read_at(core->io, addr, (unsigned char *)buf.data(), buf.size()); QString strVal = QString(buf); // Indicate that the string is longer than the printed value if (strVal.size() == buf.size()) { @@ -1611,7 +1638,7 @@ void CutterCore::setCurrentDebugThread(int tid) } emit debugTaskStateChanged(); - connect(debugTask.data(), &RizinTask::finished, this, [this] () { + connect(debugTask.data(), &RizinTask::finished, this, [this]() { debugTask.clear(); emit registersChanged(); emit refreshCodeViews(); @@ -1631,7 +1658,7 @@ void CutterCore::setCurrentDebugProcess(int pid) } emit debugTaskStateChanged(); - connect(debugTask.data(), &RizinTask::finished, this, [this] () { + connect(debugTask.data(), &RizinTask::finished, this, [this]() { debugTask.clear(); emit registersChanged(); emit refreshCodeViews(); @@ -1658,7 +1685,7 @@ void CutterCore::startDebug() emit debugTaskStateChanged(); - connect(debugTask.data(), &RizinTask::finished, this, [this] () { + connect(debugTask.data(), &RizinTask::finished, this, [this]() { if (debugTaskDialog) { delete debugTaskDialog; } @@ -1697,7 +1724,7 @@ void CutterCore::startEmulation() emit debugTaskStateChanged(); - connect(debugTask.data(), &RizinTask::finished, this, [this] () { + connect(debugTask.data(), &RizinTask::finished, this, [this]() { if (debugTaskDialog) { delete debugTaskDialog; } @@ -1739,7 +1766,7 @@ void CutterCore::attachRemote(const QString &uri) asyncCmd("e cfg.debug = true; oodf " + uri, debugTask); emit debugTaskStateChanged(); - connect(debugTask.data(), &RizinTask::finished, this, [this, uri] () { + connect(debugTask.data(), &RizinTask::finished, this, [this, uri]() { if (debugTaskDialog) { delete debugTaskDialog; } @@ -1749,7 +1776,7 @@ void CutterCore::attachRemote(const QString &uri) QJsonArray openFilesArray = getOpenedFiles(); for (QJsonValue value : openFilesArray) { QJsonObject openFile = value.toObject(); - QString fileUri= openFile["uri"].toString(); + QString fileUri = openFile["uri"].toString(); if (!fileUri.compare(uri)) { connected = true; } @@ -1793,7 +1820,7 @@ void CutterCore::attachDebug(int pid) asyncCmd("e cfg.debug = true; oodf dbg://" + QString::number(pid), debugTask); emit debugTaskStateChanged(); - connect(debugTask.data(), &RizinTask::finished, this, [this, pid] () { + connect(debugTask.data(), &RizinTask::finished, this, [this, pid]() { if (debugTaskDialog) { delete debugTaskDialog; } @@ -1845,13 +1872,14 @@ void CutterCore::stopDebug() currentlyEmulating = false; } else if (currentlyAttachedToPID != -1) { // Use cmd because cmdRaw would not work with command concatenation - cmd(QString("dp- %1; o %2; .ar-").arg( - QString::number(currentlyAttachedToPID), currentlyOpenFile)); + cmd(QString("dp- %1; o %2; .ar-") + .arg(QString::number(currentlyAttachedToPID), currentlyOpenFile)); currentlyAttachedToPID = -1; } else { QString ptraceFiles = ""; // close ptrace file descriptors left open - QJsonArray openFilesArray = cmdj("oj").array();; + QJsonArray openFilesArray = cmdj("oj").array(); + ; for (QJsonValue value : openFilesArray) { QJsonObject openFile = value.toObject(); QString URI = openFile["uri"].toString(); @@ -1895,7 +1923,7 @@ void CutterCore::continueDebug() } emit debugTaskStateChanged(); - connect(debugTask.data(), &RizinTask::finished, this, [this] () { + connect(debugTask.data(), &RizinTask::finished, this, [this]() { debugTask.clear(); syncAndSeekProgramCounter(); emit registersChanged(); @@ -1923,7 +1951,7 @@ void CutterCore::continueUntilDebug(QString offset) } emit debugTaskStateChanged(); - connect(debugTask.data(), &RizinTask::finished, this, [this] () { + connect(debugTask.data(), &RizinTask::finished, this, [this]() { debugTask.clear(); syncAndSeekProgramCounter(); emit registersChanged(); @@ -1952,7 +1980,7 @@ void CutterCore::continueUntilCall() } emit debugTaskStateChanged(); - connect(debugTask.data(), &RizinTask::finished, this, [this] () { + connect(debugTask.data(), &RizinTask::finished, this, [this]() { debugTask.clear(); syncAndSeekProgramCounter(); emit debugTaskStateChanged(); @@ -1978,7 +2006,7 @@ void CutterCore::continueUntilSyscall() } emit debugTaskStateChanged(); - connect(debugTask.data(), &RizinTask::finished, this, [this] () { + connect(debugTask.data(), &RizinTask::finished, this, [this]() { debugTask.clear(); syncAndSeekProgramCounter(); emit debugTaskStateChanged(); @@ -2004,7 +2032,7 @@ void CutterCore::stepDebug() } emit debugTaskStateChanged(); - connect(debugTask.data(), &RizinTask::finished, this, [this] () { + connect(debugTask.data(), &RizinTask::finished, this, [this]() { debugTask.clear(); syncAndSeekProgramCounter(); emit debugTaskStateChanged(); @@ -2030,7 +2058,7 @@ void CutterCore::stepOverDebug() } emit debugTaskStateChanged(); - connect(debugTask.data(), &RizinTask::finished, this, [this] () { + connect(debugTask.data(), &RizinTask::finished, this, [this]() { debugTask.clear(); syncAndSeekProgramCounter(); emit debugTaskStateChanged(); @@ -2050,7 +2078,7 @@ void CutterCore::stepOutDebug() return; } - connect(debugTask.data(), &RizinTask::finished, this, [this] () { + connect(debugTask.data(), &RizinTask::finished, this, [this]() { debugTask.clear(); syncAndSeekProgramCounter(); emit debugTaskStateChanged(); @@ -2110,8 +2138,7 @@ void CutterCore::addBreakpoint(const BreakpointDescription &config) module = moduleNameData.data(); } breakpoint = rz_debug_bp_add(core->dbg, address, (config.hw && watchpoint_prot == 0), - watchpoint_prot, watchpoint_prot, - module, config.moduleDelta); + watchpoint_prot, watchpoint_prot, module, config.moduleDelta); if (!breakpoint) { QMessageBox::critical(nullptr, tr("Breakpoint error"), tr("Failed to create breakpoint")); return; @@ -2128,8 +2155,8 @@ void CutterCore::addBreakpoint(const BreakpointDescription &config) } int index = std::find(core->dbg->bp->bps_idx, - core->dbg->bp->bps_idx + core->dbg->bp->bps_idx_count, - breakpoint) - core->dbg->bp->bps_idx; + core->dbg->bp->bps_idx + core->dbg->bp->bps_idx_count, breakpoint) + - core->dbg->bp->bps_idx; breakpoint->enabled = config.enabled; if (config.trace) { @@ -2152,7 +2179,7 @@ void CutterCore::updateBreakpoint(int index, const BreakpointDescription &config } // Delete by index currently buggy, // required for breakpoints with non address based position - //rz_bp_del_index(core->dbg->bp, index); + // rz_bp_del_index(core->dbg->bp, index); addBreakpoint(config); } @@ -2230,7 +2257,7 @@ QList CutterCore::getBreakpoints() { CORE_LOCK(); QList ret; - //TODO: use higher level API, don't touch rizin bps_idx directly + // TODO: use higher level API, don't touch rizin bps_idx directly for (int i = 0; i < core->dbg->bp->bps_idx_count; i++) { if (auto bpi = core->dbg->bp->bps_idx[i]) { ret.push_back(breakpointDescriptionFromRizin(i, bpi)); @@ -2240,7 +2267,6 @@ QList CutterCore::getBreakpoints() return ret; } - QList CutterCore::getBreakpointsAddresses() { QList bpAddresses; @@ -2257,10 +2283,9 @@ QList CutterCore::getBreakpointsInFunction(RVA funcAddr) QList functionBreakpoints; // Use std manipulations to take only the breakpoints that belong to this function - std::copy_if(allBreakpoints.begin(), - allBreakpoints.end(), - std::back_inserter(functionBreakpoints), - [this, funcAddr](RVA BPadd) { return getFunctionStart(BPadd) == funcAddr; }); + std::copy_if(allBreakpoints.begin(), allBreakpoints.end(), + std::back_inserter(functionBreakpoints), + [this, funcAddr](RVA BPadd) { return getFunctionStart(BPadd) == funcAddr; }); return functionBreakpoints; } @@ -2399,9 +2424,7 @@ QStringList CutterCore::getAsmPluginNames() QStringList ret; RzAsmPlugin *ap; - CutterRListForeach(core->rasm->plugins, it, RzAsmPlugin, ap) { - ret << ap->name; - } + CutterRListForeach(core->rasm->plugins, it, RzAsmPlugin, ap) { ret << ap->name; } return ret; } @@ -2413,9 +2436,7 @@ QStringList CutterCore::getAnalPluginNames() QStringList ret; RzAnalysisPlugin *ap; - CutterRListForeach(core->analysis->plugins, it, RzAnalysisPlugin, ap) { - ret << ap->name; - } + CutterRListForeach(core->analysis->plugins, it, RzAnalysisPlugin, ap) { ret << ap->name; } return ret; } @@ -2498,7 +2519,8 @@ QList CutterCore::getRAsmPluginDescriptions() QList ret; RzAsmPlugin *ap; - CutterRListForeach(core->rasm->plugins, it, RzAsmPlugin, ap) { + CutterRListForeach(core->rasm->plugins, it, RzAsmPlugin, ap) + { RzAsmPluginDescription plugin; plugin.name = ap->name; @@ -2524,17 +2546,18 @@ QList CutterCore::getAllFunctions() RzListIter *iter; RzAnalysisFunction *fcn; - CutterRListForeach (core->analysis->fcns, iter, RzAnalysisFunction, fcn) { + CutterRListForeach(core->analysis->fcns, iter, RzAnalysisFunction, fcn) + { FunctionDescription function; function.offset = fcn->addr; function.linearSize = rz_analysis_function_linear_size(fcn); - function.nargs = rz_analysis_var_count(core->analysis, fcn, 'b', 1) + - rz_analysis_var_count(core->analysis, fcn, 'r', 1) + - rz_analysis_var_count(core->analysis, fcn, 's', 1); - function.nlocals = rz_analysis_var_count(core->analysis, fcn, 'b', 0) + - rz_analysis_var_count(core->analysis, fcn, 'r', 0) + - rz_analysis_var_count(core->analysis, fcn, 's', 0); - function.nbbs = rz_list_length (fcn->bbs); + function.nargs = rz_analysis_var_count(core->analysis, fcn, 'b', 1) + + rz_analysis_var_count(core->analysis, fcn, 'r', 1) + + rz_analysis_var_count(core->analysis, fcn, 's', 1); + function.nlocals = rz_analysis_var_count(core->analysis, fcn, 'b', 0) + + rz_analysis_var_count(core->analysis, fcn, 'r', 0) + + rz_analysis_var_count(core->analysis, fcn, 's', 0); + function.nbbs = rz_list_length(fcn->bbs); function.calltype = fcn->cc ? QString::fromUtf8(fcn->cc) : QString(); function.name = fcn->name ? QString::fromUtf8(fcn->name) : QString(); function.edges = rz_analysis_function_count_edges(fcn, nullptr); @@ -2604,7 +2627,8 @@ QList CutterCore::getAllSymbols() RzBinSymbol *bs; if (core && core->bin && core->bin->cur && core->bin->cur->o) { - CutterRListForeach(core->bin->cur->o->symbols, it, RzBinSymbol, bs) { + CutterRListForeach(core->bin->cur->o->symbols, it, RzBinSymbol, bs) + { QString type = QString(bs->bind) + " " + QString(bs->type); SymbolDescription symbol; symbol.vaddr = bs->vaddr; @@ -2617,7 +2641,8 @@ QList CutterCore::getAllSymbols() /* list entrypoints as symbols too */ int n = 0; RzBinAddr *entry; - CutterRListForeach(core->bin->cur->o->entries, it, RzBinAddr, entry) { + CutterRListForeach(core->bin->cur->o->entries, it, RzBinAddr, entry) + { SymbolDescription symbol; symbol.vaddr = entry->vaddr; symbol.name = QString("entry") + QString::number(n++); @@ -2715,7 +2740,8 @@ QList CutterCore::getAllRelocs() auto relocs = core->bin->cur->o->relocs; RBIter iter; RzBinReloc *br; - rz_rbtree_foreach (relocs, iter, br, RzBinReloc, vrb) { + rz_rbtree_foreach(relocs, iter, br, RzBinReloc, vrb) + { RelocDescription reloc; reloc.vaddr = br->vaddr; @@ -2829,7 +2855,7 @@ QList CutterCore::getAllSections() section.paddr = sectionObject[RJsonKey::paddr].toVariant().toULongLong(); section.size = sectionObject[RJsonKey::size].toVariant().toULongLong(); section.perm = sectionObject[RJsonKey::perm].toString(); - section.entropy = sectionObject[RJsonKey::entropy].toString(); + section.entropy = sectionObject[RJsonKey::entropy].toString(); sections << section; } @@ -2868,7 +2894,7 @@ QList CutterCore::getAllSegments() segment.paddr = segmentObject[RJsonKey::paddr].toVariant().toULongLong(); segment.size = segmentObject[RJsonKey::size].toVariant().toULongLong(); segment.vsize = segmentObject[RJsonKey::vsize].toVariant().toULongLong(); - segment.perm = segmentObject[RJsonKey::perm].toString(); + segment.perm = segmentObject[RJsonKey::perm].toString(); ret << segment; } @@ -3015,7 +3041,8 @@ QList CutterCore::getAllAnalClasses(bool sorted) SdbListIter *it; void *entry; - ls_foreach(l, it, entry) { + ls_foreach(l, it, entry) + { auto kv = reinterpret_cast(entry); ret.append(QString::fromUtf8(reinterpret_cast(kv->base.key))); } @@ -3035,7 +3062,8 @@ QList CutterCore::getAnalClassMethods(const QString &cls) ret.reserve(static_cast(meths->len)); RzAnalysisMethod *meth; - CutterRVectorForeach(meths, meth, RzAnalysisMethod) { + CutterRVectorForeach(meths, meth, RzAnalysisMethod) + { AnalMethodDescription desc; desc.name = QString::fromUtf8(meth->name); desc.addr = meth->addr; @@ -3059,7 +3087,8 @@ QList CutterCore::getAnalClassBaseClasses(const QStrin ret.reserve(static_cast(bases->len)); RzAnalysisBaseClass *base; - CutterRVectorForeach(bases, base, RzAnalysisBaseClass) { + CutterRVectorForeach(bases, base, RzAnalysisBaseClass) + { AnalBaseClassDescription desc; desc.id = QString::fromUtf8(base->id); desc.offset = base->offset; @@ -3083,7 +3112,8 @@ QList CutterCore::getAnalClassVTables(const QString &cls) acVtables.reserve(static_cast(vtables->len)); RzAnalysisVTable *vtable; - CutterRVectorForeach(vtables, vtable, RzAnalysisVTable) { + CutterRVectorForeach(vtables, vtable, RzAnalysisVTable) + { AnalVTableDescription desc; desc.id = QString::fromUtf8(vtable->id); desc.offset = vtable->offset; @@ -3104,7 +3134,8 @@ void CutterCore::createNewClass(const QString &cls) void CutterCore::renameClass(const QString &oldName, const QString &newName) { CORE_LOCK(); - rz_analysis_class_rename(core->analysis, oldName.toUtf8().constData(), newName.toUtf8().constData()); + rz_analysis_class_rename(core->analysis, oldName.toUtf8().constData(), + newName.toUtf8().constData()); } void CutterCore::deleteClass(const QString &cls) @@ -3117,7 +3148,9 @@ bool CutterCore::getAnalMethod(const QString &cls, const QString &meth, AnalMeth { CORE_LOCK(); RzAnalysisMethod analMeth; - if (rz_analysis_class_method_get(core->analysis, cls.toUtf8().constData(), meth.toUtf8().constData(), &analMeth) != RZ_ANALYSIS_CLASS_ERR_SUCCESS) { + if (rz_analysis_class_method_get(core->analysis, cls.toUtf8().constData(), + meth.toUtf8().constData(), &analMeth) + != RZ_ANALYSIS_CLASS_ERR_SUCCESS) { return false; } desc->name = QString::fromUtf8(analMeth.name); @@ -3131,17 +3164,20 @@ void CutterCore::setAnalMethod(const QString &className, const AnalMethodDescrip { CORE_LOCK(); RzAnalysisMethod analMeth; - analMeth.name = strdup (meth.name.toUtf8().constData()); + analMeth.name = strdup(meth.name.toUtf8().constData()); analMeth.addr = meth.addr; analMeth.vtable_offset = meth.vtableOffset; rz_analysis_class_method_set(core->analysis, className.toUtf8().constData(), &analMeth); rz_analysis_class_method_fini(&analMeth); } -void CutterCore::renameAnalMethod(const QString &className, const QString &oldMethodName, const QString &newMethodName) +void CutterCore::renameAnalMethod(const QString &className, const QString &oldMethodName, + const QString &newMethodName) { CORE_LOCK(); - rz_analysis_class_method_rename(core->analysis, className.toUtf8().constData(), oldMethodName.toUtf8().constData(), newMethodName.toUtf8().constData()); + rz_analysis_class_method_rename(core->analysis, className.toUtf8().constData(), + oldMethodName.toUtf8().constData(), + newMethodName.toUtf8().constData()); } QList CutterCore::getAllResources() @@ -3237,7 +3273,7 @@ QList CutterCore::getAllUnions() QList unions; QJsonArray typesArray = cmdj("tuj").array(); - for (const QJsonValue value: typesArray) { + for (const QJsonValue value : typesArray) { QJsonObject typeObject = value.toObject(); TypeDescription exp; @@ -3257,7 +3293,7 @@ QList CutterCore::getAllStructs() QList structs; QJsonArray typesArray = cmdj("tsj").array(); - for (const QJsonValue value: typesArray) { + for (const QJsonValue value : typesArray) { QJsonObject typeObject = value.toObject(); TypeDescription exp; @@ -3277,7 +3313,7 @@ QList CutterCore::getAllEnums() QList enums; QJsonObject typesObject = cmdj("tej").object(); - for (QString key: typesObject.keys()) { + for (QString key : typesObject.keys()) { TypeDescription exp; exp.type = key; exp.size = 0; @@ -3294,7 +3330,7 @@ QList CutterCore::getAllTypedefs() QList typeDefs; QJsonObject typesObject = cmdj("ttj").object(); - for (QString key: typesObject.keys()) { + for (QString key : typesObject.keys()) { TypeDescription exp; exp.type = key; exp.size = 0; @@ -3313,11 +3349,11 @@ QString CutterCore::addTypes(const char *str) QString error; if (!parsed) { - if (error_msg) { - error = error_msg; - rz_mem_free(error_msg); - } - return error; + if (error_msg) { + error = error_msg; + rz_mem_free(error_msg); + } + return error; } rz_analysis_save_parsed_type(core->analysis, parsed); @@ -3343,9 +3379,9 @@ QString CutterCore::getTypeAsC(QString name, QString category) output = cmdRaw(QString("tsc %1").arg(typeName)); } else if (category == "Union") { output = cmdRaw(QString("tuc %1").arg(typeName)); - } else if(category == "Enum") { + } else if (category == "Enum") { output = cmdRaw(QString("tec %1").arg(typeName)); - } else if(category == "Typedef") { + } else if (category == "Typedef") { output = cmdRaw(QString("ttc %1").arg(typeName)); } return output; @@ -3381,8 +3417,12 @@ QList CutterCore::getAllSearch(QString searchFor, QString spa exp.code += gadget[RJsonKey::opcode].toString() + "; "; } - exp.offset = - searchObject[RJsonKey::opcodes].toArray().first().toObject()[RJsonKey::offset].toVariant().toULongLong(); + exp.offset = searchObject[RJsonKey::opcodes] + .toArray() + .first() + .toObject()[RJsonKey::offset] + .toVariant() + .toULongLong(); exp.size = searchObject[RJsonKey::size].toVariant().toULongLong(); searchRef << exp; @@ -3462,7 +3502,8 @@ BlockStatistics CutterCore::getBlockStatistics(unsigned int blocksCount) return blockStats; } -QList CutterCore::getXRefsForVariable(QString variableName, bool findWrites, RVA offset) +QList CutterCore::getXRefsForVariable(QString variableName, bool findWrites, + RVA offset) { QList xrefList = QList(); QJsonArray xrefsArray; @@ -3561,7 +3602,7 @@ void CutterCore::addFlag(RVA offset, QString name, RVA size) QString CutterCore::listFlagsAsStringAt(RVA addr) { CORE_LOCK(); - char *flagList = rz_flag_get_liststr (core->flags, addr); + char *flagList = rz_flag_get_liststr(core->flags, addr); QString result = fromOwnedCharPtr(flagList); return result; } @@ -3572,7 +3613,7 @@ QString CutterCore::nearestFlag(RVA offset, RVA *flagOffsetOut) QString name = r.value("name").toString(); if (flagOffsetOut) { int queryOffset = r.value("offset").toInt(0); - *flagOffsetOut = offset + static_cast(-queryOffset); + *flagOffsetOut = offset + static_cast(-queryOffset); } return name; } @@ -3611,7 +3652,7 @@ void CutterCore::handleREvent(int type, void *data) break; } case RZ_EVENT_DEBUG_PROCESS_FINISHED: { - auto ev = reinterpret_cast(data); + auto ev = reinterpret_cast(data); emit debugProcessFinished(ev->pid); break; } @@ -3642,8 +3683,9 @@ void CutterCore::loadPDB(const QString &file) QList CutterCore::disassembleLines(RVA offset, int lines) { - QJsonArray array = cmdj(QString("pdJ ") + QString::number(lines) + QString(" @ ") + QString::number( - offset)).array(); + QJsonArray array = cmdj(QString("pdJ ") + QString::number(lines) + QString(" @ ") + + QString::number(offset)) + .array(); QList r; for (const QJsonValueRef &value : array) { @@ -3651,21 +3693,18 @@ QList CutterCore::disassembleLines(RVA offset, int lines) DisassemblyLine line; line.offset = object[RJsonKey::offset].toVariant().toULongLong(); line.text = ansiEscapeToHtml(object[RJsonKey::text].toString()); - const auto& arrow = object[RJsonKey::arrow]; - line.arrow = arrow.isNull() - ? RVA_INVALID - : arrow.toVariant().toULongLong(); + const auto &arrow = object[RJsonKey::arrow]; + line.arrow = arrow.isNull() ? RVA_INVALID : arrow.toVariant().toULongLong(); r << line; } return r; } - /** * @brief return hexdump of from an by a given formats * @param address - the address from which to print the hexdump - * @param size - number of bytes to print + * @param size - number of bytes to print * @param format - the type of hexdump (qwords, words. decimal, etc) */ QString CutterCore::hexdump(RVA address, int size, HexdumpFormats format) @@ -3691,10 +3730,7 @@ QString CutterCore::hexdump(RVA address, int size, HexdumpFormats format) break; } - return cmdRawAt(QString("%1 %2") - .arg(command) - .arg(size), - address); + return cmdRawAt(QString("%1 %2").arg(command).arg(size), address); } QByteArray CutterCore::hexStringToBytes(const QString &hex) @@ -3728,7 +3764,8 @@ QString CutterCore::getVersionInformation() { int i; QString versionInfo; - struct vcs_t { + struct vcs_t + { const char *name; const char *(*callback)(); } vcs[] = { @@ -3755,12 +3792,12 @@ QString CutterCore::getVersionInformation() { "rz_syscall", &rz_syscall_version }, { "rz_util", &rz_util_version }, /* ... */ - {NULL, NULL} + { NULL, NULL } }; versionInfo.append(QString("%1 rz\n").arg(RZ_GITTAP)); for (i = 0; vcs[i].name; i++) { struct vcs_t *v = &vcs[i]; - const char *name = v->callback (); + const char *name = v->callback(); versionInfo.append(QString("%1 %2\n").arg(name, v->name)); } return versionInfo; @@ -3794,12 +3831,12 @@ QString CutterCore::ansiEscapeToHtml(const QString &text) return r; } -BasicBlockHighlighter* CutterCore::getBBHighlighter() +BasicBlockHighlighter *CutterCore::getBBHighlighter() { return bbHighlighter; } -BasicInstructionHighlighter* CutterCore::getBIHighlighter() +BasicInstructionHighlighter *CutterCore::getBIHighlighter() { return &biHighlighter; } @@ -3845,18 +3882,18 @@ void CutterCore::setWriteMode(bool enabled) // New mode is the same as current and IO Cache is disabled. Do nothing. return; } - + // Change from read-only to write-mode if (enabled && !writeModeState) { cmdRaw("oo+"); - // Change from write-mode to read-only + // Change from write-mode to read-only } else { cmdRaw("oo"); } // Disable cache mode because we specifically set write or // read-only modes. setIOCache(false); - writeModeChanged (enabled); + writeModeChanged(enabled); emit ioModeChanged(); } @@ -3864,24 +3901,25 @@ bool CutterCore::isWriteModeEnabled() { using namespace std; QJsonArray ans = cmdj("oj").array(); - return find_if(begin(ans), end(ans), [](const QJsonValue &v) { - return v.toObject().value("raised").toBool(); - })->toObject().value("writable").toBool(); + return find_if(begin(ans), end(ans), + [](const QJsonValue &v) { return v.toObject().value("raised").toBool(); }) + ->toObject() + .value("writable") + .toBool(); } /** * @brief get a compact disassembly preview for tooltips * @param address - the address from which to print the disassembly - * @param num_of_lines - number of instructions to print + * @param num_of_lines - number of instructions to print */ QStringList CutterCore::getDisassemblyPreview(RVA address, int num_of_lines) { - QList disassemblyLines; - { - // temporarily simplify the disasm output to get it colorful and simple to read - TempConfig tempConfig; - tempConfig - .set("scr.color", COLOR_MODE_16M) + QList disassemblyLines; + { + // temporarily simplify the disasm output to get it colorful and simple to read + TempConfig tempConfig; + tempConfig.set("scr.color", COLOR_MODE_16M) .set("asm.lines", false) .set("asm.var", false) .set("asm.comments", false) @@ -3891,38 +3929,38 @@ QStringList CutterCore::getDisassemblyPreview(RVA address, int num_of_lines) .set("asm.lines.bb", false) .set("asm.bb.line", false); - disassemblyLines = disassembleLines(address, num_of_lines + 1); - } - QStringList disasmPreview; - for (const DisassemblyLine &line : disassemblyLines) { - disasmPreview << line.text; - if (disasmPreview.length() >= num_of_lines) { - disasmPreview << "..."; - break; - } - } - if (!disasmPreview.isEmpty()) { - return disasmPreview; - } else { - return QStringList(); + disassemblyLines = disassembleLines(address, num_of_lines + 1); + } + QStringList disasmPreview; + for (const DisassemblyLine &line : disassemblyLines) { + disasmPreview << line.text; + if (disasmPreview.length() >= num_of_lines) { + disasmPreview << "..."; + break; } + } + if (!disasmPreview.isEmpty()) { + return disasmPreview; + } else { + return QStringList(); + } } /** * @brief get a compact hexdump preview for tooltips * @param address - the address from which to print the hexdump - * @param size - number of bytes to print + * @param size - number of bytes to print */ QString CutterCore::getHexdumpPreview(RVA address, int size) -{ +{ // temporarily simplify the disasm output to get it colorful and simple to read TempConfig tempConfig; - tempConfig - .set("scr.color", COLOR_MODE_16M) - .set("asm.offset", true) - .set("hex.header", false) - .set("hex.cols", 16); - return ansiEscapeToHtml(hexdump(address, size, HexdumpFormats::Normal)).replace(QLatin1Char('\n'), "
"); + tempConfig.set("scr.color", COLOR_MODE_16M) + .set("asm.offset", true) + .set("hex.header", false) + .set("hex.cols", 16); + return ansiEscapeToHtml(hexdump(address, size, HexdumpFormats::Normal)) + .replace(QLatin1Char('\n'), "
"); } QByteArray CutterCore::ioRead(RVA addr, int len) @@ -3941,5 +3979,5 @@ QByteArray CutterCore::ioRead(RVA addr, int len) array.fill(0xff); } - return array; + return array; } diff --git a/src/core/Cutter.h b/src/core/Cutter.h index ef3c4678..2a0ba6dd 100644 --- a/src/core/Cutter.h +++ b/src/core/Cutter.h @@ -33,7 +33,7 @@ class RizinTaskDialog; class RzCoreLocked; -class CUTTER_EXPORT CutterCore: public QObject +class CUTTER_EXPORT CutterCore : public QObject { Q_OBJECT @@ -52,7 +52,7 @@ public: AsyncTaskManager *getAsyncTaskManager() { return asyncTaskManager; } - RVA getOffset() const { return core_->offset; } + RVA getOffset() const { return core_->offset; } /* Core functions (commands) */ static QString sanitizeStringForCommand(QString s); @@ -75,12 +75,17 @@ public: * If you want to seek to an address, you should use CutterCore::seek. */ bool asyncCmd(const char *str, QSharedPointer &task); - bool asyncCmd(const QString &str, QSharedPointer &task) { return asyncCmd(str.toUtf8().constData(), task); } + bool asyncCmd(const QString &str, QSharedPointer &task) + { + return asyncCmd(str.toUtf8().constData(), task); + } /** * @brief Execute a Rizin command \a cmd. By nature, the API - * is executing raw commands, and thus ignores multiple commands and overcome command injections. - * @param cmd - a raw command to execute. Passing multiple commands (e.g "px 5; pd 7 && pdf") will result in them treated as arguments to first command. + * is executing raw commands, and thus ignores multiple commands and overcome command + * injections. + * @param cmd - a raw command to execute. Passing multiple commands (e.g "px 5; pd 7 && pdf") + * will result in them treated as arguments to first command. * @return the output of the command */ QString cmdRaw(const char *cmd); @@ -91,12 +96,12 @@ public: QString cmdRaw(const QString &cmd) { return cmdRaw(cmd.toUtf8().constData()); }; /** - * @brief Execute a Rizin command \a cmd at \a address. The function will preform a silent seek to the address - * without triggering the seekChanged event nor adding new entries to the seek history. By nature, the - * API is executing a single command without going through Rizin shell, and thus ignores multiple commands - * and tries to overcome command injections. - * @param cmd - a raw command to execute. If multiple commands will be passed (e.g "px 5; pd 7 && pdf") then - * only the first command will be executed. + * @brief Execute a Rizin command \a cmd at \a address. The function will preform a silent seek + * to the address without triggering the seekChanged event nor adding new entries to the seek + * history. By nature, the API is executing a single command without going through Rizin shell, + * and thus ignores multiple commands and tries to overcome command injections. + * @param cmd - a raw command to execute. If multiple commands will be passed (e.g "px 5; pd 7 + * && pdf") then only the first command will be executed. * @param address - an address to which Cutter will temporarily seek. * @return the output of the command */ @@ -105,12 +110,18 @@ public: /** * @brief a wrapper around cmdRawAt(const char *cmd, RVA address). */ - QString cmdRawAt(const QString &str, RVA address) { return cmdRawAt(str.toUtf8().constData(), address); } + QString cmdRawAt(const QString &str, RVA address) + { + return cmdRawAt(str.toUtf8().constData(), address); + } QJsonDocument cmdj(const char *str); QJsonDocument cmdj(const QString &str) { return cmdj(str.toUtf8().constData()); } QJsonDocument cmdjAt(const char *str, RVA address); - QStringList cmdList(const char *str) { return cmd(str).split(QLatin1Char('\n'), CUTTER_QT_SKIP_EMPTY_PARTS); } + QStringList cmdList(const char *str) + { + return cmd(str).split(QLatin1Char('\n'), CUTTER_QT_SKIP_EMPTY_PARTS); + } QStringList cmdList(const QString &str) { return cmdList(str.toUtf8().constData()); } QString cmdTask(const QString &str); QJsonDocument cmdjTask(const QString &str); @@ -132,7 +143,10 @@ public: * If you want to seek to an address, you should use CutterCore::seek. */ bool asyncCmdEsil(const char *command, QSharedPointer &task); - bool asyncCmdEsil(const QString &command, QSharedPointer &task) { return asyncCmdEsil(command.toUtf8().constData(), task); } + bool asyncCmdEsil(const QString &command, QSharedPointer &task) + { + return asyncCmdEsil(command.toUtf8().constData(), task); + } QString getVersionInformation(); QJsonDocument parseJson(const char *res, const char *cmd = nullptr); @@ -253,7 +267,8 @@ public: void renameClass(const QString &oldName, const QString &newName); void deleteClass(const QString &cls); bool getAnalMethod(const QString &cls, const QString &meth, AnalMethodDescription *desc); - void renameAnalMethod(const QString &className, const QString &oldMethodName, const QString &newMethodName); + void renameAnalMethod(const QString &className, const QString &oldMethodName, + const QString &newMethodName); void setAnalMethod(const QString &cls, const AnalMethodDescription &meth); /* File related methods */ @@ -445,7 +460,8 @@ public: * Register a new decompiler * * The decompiler must have a unique id, otherwise this method will fail. - * The decompiler's parent will be set to this CutterCore instance, so it will automatically be freed later. + * The decompiler's parent will be set to this CutterCore instance, so it will automatically be + * freed later. * * @return whether the decompiler was registered successfully */ @@ -536,7 +552,6 @@ public: */ QString getTypeAsC(QString name, QString category); - /** * @brief Adds new types * It first uses the rz_parse_c_string() function from Rizin API to parse the @@ -572,11 +587,12 @@ public: * @brief Fetches all the writes or reads to the specified local variable 'variableName' * in the function in which the specified offset is a part of. * @param variableName Name of the local variable. - * @param findWrites If this is true, then locations at which modification happen to the specified - * local variable is fetched. Else, the locations at which the local is variable is read is fetched. + * @param findWrites If this is true, then locations at which modification happen to the + * specified local variable is fetched. Else, the locations at which the local is variable is + * read is fetched. * @param offset An offset in the function in which the specified local variable exist. - * @return A list of XrefDescriptions that contains details of all the writes or reads that happen to the - * variable 'variableName'. + * @return A list of XrefDescriptions that contains details of all the writes or reads that + * happen to the variable 'variableName'. */ QList getXRefsForVariable(QString variableName, bool findWrites, RVA offset); QList getXRefs(RVA addr, bool to, bool whole_function, @@ -622,9 +638,9 @@ public: void commitWriteCache(); /** - * @brief Enable or disable Write mode. When the file is opened in write mode, any changes to it will be immediately - * committed to the file on disk, thus modify the file. This function wrap Rizin function which re-open the file with - * the desired permissions. + * @brief Enable or disable Write mode. When the file is opened in write mode, any changes to it + * will be immediately committed to the file on disk, thus modify the file. This function wrap + * Rizin function which re-open the file with the desired permissions. * @param enabled */ void setWriteMode(bool enabled); @@ -732,7 +748,7 @@ private: class CUTTER_EXPORT RzCoreLocked { - CutterCore * const core; + CutterCore *const core; public: explicit RzCoreLocked(CutterCore *core); diff --git a/src/core/CutterCommon.h b/src/core/CutterCommon.h index 47f74b9f..8f31a5e3 100644 --- a/src/core/CutterCommon.h +++ b/src/core/CutterCommon.h @@ -10,17 +10,20 @@ // Workaround for compile errors on Windows #ifdef Q_OS_WIN -#undef min -#undef max +# undef min +# undef max #endif // Q_OS_WIN // Rizin list iteration macros -#define CutterRListForeach(list, it, type, x) \ - if (list) for (it = list->head; it && ((x=static_cast(it->data))); it = it->n) +#define CutterRListForeach(list, it, type, x) \ + if (list) \ + for (it = list->head; it && ((x = static_cast(it->data))); it = it->n) -#define CutterRVectorForeach(vec, it, type) \ - if ((vec) && (vec)->a) \ - for (it = (type *)(vec)->a; (char *)it != (char *)(vec)->a + ((vec)->len * (vec)->elem_size); it = (type *)((char *)it + (vec)->elem_size)) +#define CutterRVectorForeach(vec, it, type) \ + if ((vec) && (vec)->a) \ + for (it = (type *)(vec)->a; \ + (char *)it != (char *)(vec)->a + ((vec)->len * (vec)->elem_size); \ + it = (type *)((char *)it + (vec)->elem_size)) // Global information for Cutter #define APPNAME "Cutter" @@ -31,7 +34,8 @@ typedef ut64 RVA; /** - * @brief Maximum value of RVA. Do NOT use this for specifying invalid values, use RVA_INVALID instead. + * @brief Maximum value of RVA. Do NOT use this for specifying invalid values, use RVA_INVALID + * instead. */ #define RVA_MAX UT64_MAX @@ -56,20 +60,18 @@ inline QString RHexString(RVA size) } #ifdef CUTTER_SOURCE_BUILD -#define CUTTER_EXPORT Q_DECL_EXPORT +# define CUTTER_EXPORT Q_DECL_EXPORT #else -#define CUTTER_EXPORT Q_DECL_IMPORT +# define CUTTER_EXPORT Q_DECL_IMPORT #endif - #if defined(__has_cpp_attribute) - #if __has_cpp_attribute(deprecated) - #define CUTTER_DEPRECATED(msg) [[deprecated(msg)]] - #endif +# if __has_cpp_attribute(deprecated) +# define CUTTER_DEPRECATED(msg) [[deprecated(msg)]] +# endif #endif #if !defined(CUTTER_DEPRECATED) -#define CUTTER_DEPRECATED(msg) +# define CUTTER_DEPRECATED(msg) #endif #endif // CUTTERCORE_H - diff --git a/src/core/CutterDescriptions.h b/src/core/CutterDescriptions.h index a9b6b7e7..166a7d85 100644 --- a/src/core/CutterDescriptions.h +++ b/src/core/CutterDescriptions.h @@ -12,7 +12,8 @@ #include #include "core/CutterCommon.h" -struct FunctionDescription { +struct FunctionDescription +{ RVA offset; RVA linearSize; RVA nargs; @@ -31,7 +32,8 @@ struct FunctionDescription { } }; -struct ImportDescription { +struct ImportDescription +{ RVA plt; int ordinal; QString bind; @@ -40,7 +42,8 @@ struct ImportDescription { QString libname; }; -struct ExportDescription { +struct ExportDescription +{ RVA vaddr; RVA paddr; RVA size; @@ -69,40 +72,46 @@ struct ZignatureDescription QStringList refs; }; -struct TypeDescription { +struct TypeDescription +{ QString type; int size; QString format; QString category; }; -struct SearchDescription { +struct SearchDescription +{ RVA offset; int size; QString code; QString data; }; -struct SymbolDescription { +struct SymbolDescription +{ RVA vaddr; QString bind; QString type; QString name; }; -struct CommentDescription { +struct CommentDescription +{ RVA offset; QString name; }; -struct RelocDescription { +struct RelocDescription +{ RVA vaddr; RVA paddr; QString type; QString name; }; -struct StringDescription { +struct StringDescription +{ RVA vaddr; QString string; QString type; @@ -111,18 +120,21 @@ struct StringDescription { ut32 size; }; -struct FlagspaceDescription { +struct FlagspaceDescription +{ QString name; }; -struct FlagDescription { +struct FlagDescription +{ RVA offset; RVA size; QString name; QString realname; }; -struct SectionDescription { +struct SectionDescription +{ RVA vaddr; RVA paddr; RVA size; @@ -132,7 +144,8 @@ struct SectionDescription { QString entropy; }; -struct SegmentDescription { +struct SegmentDescription +{ RVA vaddr; RVA paddr; RVA size; @@ -141,7 +154,8 @@ struct SegmentDescription { QString perm; }; -struct EntrypointDescription { +struct EntrypointDescription +{ RVA vaddr; RVA paddr; RVA baddr; @@ -150,7 +164,8 @@ struct EntrypointDescription { QString type; }; -struct XrefDescription { +struct XrefDescription +{ RVA from; QString from_str; RVA to; @@ -158,14 +173,16 @@ struct XrefDescription { QString type; }; -struct RzBinPluginDescription { +struct RzBinPluginDescription +{ QString name; QString description; QString license; QString type; }; -struct RzIOPluginDescription { +struct RzIOPluginDescription +{ QString name; QString description; QString license; @@ -173,12 +190,14 @@ struct RzIOPluginDescription { QList uris; }; -struct RzCorePluginDescription { +struct RzCorePluginDescription +{ QString name; QString description; }; -struct RzAsmPluginDescription { +struct RzAsmPluginDescription +{ QString name; QString architecture; QString author; @@ -188,29 +207,34 @@ struct RzAsmPluginDescription { QString license; }; -struct DisassemblyLine { +struct DisassemblyLine +{ RVA offset; QString text; RVA arrow; }; -struct BinClassBaseClassDescription { +struct BinClassBaseClassDescription +{ QString name; RVA offset; }; -struct BinClassMethodDescription { +struct BinClassMethodDescription +{ QString name; RVA addr = RVA_INVALID; st64 vtableOffset = -1; }; -struct BinClassFieldDescription { +struct BinClassFieldDescription +{ QString name; RVA addr = RVA_INVALID; }; -struct BinClassDescription { +struct BinClassDescription +{ QString name; RVA addr = RVA_INVALID; RVA vtableAddr = RVA_INVALID; @@ -220,25 +244,29 @@ struct BinClassDescription { QList fields; }; -struct AnalMethodDescription { +struct AnalMethodDescription +{ QString name; RVA addr; st64 vtableOffset; }; -struct AnalBaseClassDescription { +struct AnalBaseClassDescription +{ QString id; RVA offset; QString className; }; -struct AnalVTableDescription { +struct AnalVTableDescription +{ QString id; ut64 offset; ut64 addr; }; -struct ResourcesDescription { +struct ResourcesDescription +{ QString name; RVA vaddr; ut64 index; @@ -247,12 +275,14 @@ struct ResourcesDescription { QString lang; }; -struct VTableDescription { +struct VTableDescription +{ RVA addr; QList methods; }; -struct BlockDescription { +struct BlockDescription +{ RVA addr; RVA size; int flags; @@ -264,14 +294,16 @@ struct BlockDescription { ut8 rwx; }; -struct BlockStatistics { +struct BlockStatistics +{ RVA from; RVA to; RVA blocksize; QList blocks; }; -struct MemoryMapDescription { +struct MemoryMapDescription +{ RVA addrStart; RVA addrEnd; QString name; @@ -280,7 +312,8 @@ struct MemoryMapDescription { QString permission; }; -struct BreakpointDescription { +struct BreakpointDescription +{ enum PositionType { Address, Named, @@ -302,26 +335,30 @@ struct BreakpointDescription { bool enabled = true; }; -struct ProcessDescription { +struct ProcessDescription +{ int pid; int uid; QString status; QString path; }; -struct RefDescription { +struct RefDescription +{ QString ref; QColor refColor; }; -struct VariableDescription { +struct VariableDescription +{ enum class RefType { SP, BP, Reg }; RefType refType; QString name; QString type; }; -struct RegisterRefValueDescription { +struct RegisterRefValueDescription +{ QString name; QString value; QString ref; diff --git a/src/core/MainWindow.cpp b/src/core/MainWindow.cpp index bd27ac69..76735810 100644 --- a/src/core/MainWindow.cpp +++ b/src/core/MainWindow.cpp @@ -117,14 +117,14 @@ #define PROJECT_FILE_FILTER tr("Rizin Project (*.rzdb)") template -T *getNewInstance(MainWindow *m) { return new T(m); } +T *getNewInstance(MainWindow *m) +{ + return new T(m); +} using namespace Cutter; -MainWindow::MainWindow(QWidget *parent) : - QMainWindow(parent), - core(Core()), - ui(new Ui::MainWindow) +MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), core(Core()), ui(new Ui::MainWindow) { tabsOnTop = false; configuration = Config(); @@ -132,9 +132,7 @@ MainWindow::MainWindow(QWidget *parent) : initUI(); } -MainWindow::~MainWindow() -{ -} +MainWindow::~MainWindow() {} void MainWindow::initUI() { @@ -146,18 +144,19 @@ void MainWindow::initUI() connect(ui->actionExtraDecompiler, &QAction::triggered, this, &MainWindow::addExtraDecompiler); connect(ui->actionExtraGraph, &QAction::triggered, this, &MainWindow::addExtraGraph); - connect(ui->actionExtraDisassembly, &QAction::triggered, this, &MainWindow::addExtraDisassembly); + connect(ui->actionExtraDisassembly, &QAction::triggered, this, + &MainWindow::addExtraDisassembly); connect(ui->actionExtraHexdump, &QAction::triggered, this, &MainWindow::addExtraHexdump); - connect(ui->actionCommitChanges, &QAction::triggered, this, [this]() { - Core()->commitWriteCache(); - }); + connect(ui->actionCommitChanges, &QAction::triggered, this, + [this]() { Core()->commitWriteCache(); }); ui->actionCommitChanges->setEnabled(false); connect(Core(), &CutterCore::ioCacheChanged, ui->actionCommitChanges, &QAction::setEnabled); widgetTypeToConstructorMap.insert(GraphWidget::getWidgetType(), getNewInstance); widgetTypeToConstructorMap.insert(DisassemblyWidget::getWidgetType(), getNewInstance); - widgetTypeToConstructorMap.insert(HexdumpWidget::getWidgetType(), getNewInstance); + widgetTypeToConstructorMap.insert(HexdumpWidget::getWidgetType(), + getNewInstance); widgetTypeToConstructorMap.insert(DecompilerWidget::getWidgetType(), getNewInstance); @@ -175,13 +174,17 @@ void MainWindow::initUI() // G and S goes to goto entry QShortcut *goto_shortcut = new QShortcut(QKeySequence(Qt::Key_G), this); - connect(goto_shortcut, &QShortcut::activated, this->omnibar, [this](){ this->omnibar->setFocus(); }); + connect(goto_shortcut, &QShortcut::activated, this->omnibar, + [this]() { this->omnibar->setFocus(); }); QShortcut *seek_shortcut = new QShortcut(QKeySequence(Qt::Key_S), this); - connect(seek_shortcut, &QShortcut::activated, this->omnibar, [this](){ this->omnibar->setFocus(); }); + connect(seek_shortcut, &QShortcut::activated, this->omnibar, + [this]() { this->omnibar->setFocus(); }); QShortcut *seek_to_func_end_shortcut = new QShortcut(QKeySequence(Qt::Key_Dollar), this); - connect(seek_to_func_end_shortcut, &QShortcut::activated, this, &MainWindow::seekToFunctionLastInstruction); + connect(seek_to_func_end_shortcut, &QShortcut::activated, this, + &MainWindow::seekToFunctionLastInstruction); QShortcut *seek_to_func_start_shortcut = new QShortcut(QKeySequence(Qt::Key_AsciiCircum), this); - connect(seek_to_func_start_shortcut, &QShortcut::activated, this, &MainWindow::seekToFunctionStart); + connect(seek_to_func_start_shortcut, &QShortcut::activated, this, + &MainWindow::seekToFunctionStart); QShortcut *refresh_shortcut = new QShortcut(QKeySequence(QKeySequence::Refresh), this); connect(refresh_shortcut, &QShortcut::activated, this, &MainWindow::refreshAll); @@ -192,13 +195,11 @@ void MainWindow::initUI() connect(core, &CutterCore::toggleDebugView, this, &MainWindow::toggleDebugView); - connect(core, &CutterCore::newMessage, - this->consoleDock, &ConsoleWidget::addOutput); - connect(core, &CutterCore::newDebugMessage, - this->consoleDock, &ConsoleWidget::addDebugOutput); + connect(core, &CutterCore::newMessage, this->consoleDock, &ConsoleWidget::addOutput); + connect(core, &CutterCore::newDebugMessage, this->consoleDock, &ConsoleWidget::addDebugOutput); - connect(core, &CutterCore::showMemoryWidgetRequested, - this, static_cast(&MainWindow::showMemoryWidget)); + connect(core, &CutterCore::showMemoryWidgetRequested, this, + static_cast(&MainWindow::showMemoryWidget)); updateTasksIndicator(); connect(core->getAsyncTaskManager(), &AsyncTaskManager::tasksChanged, this, @@ -247,7 +248,8 @@ void MainWindow::initUI() ui->menuWindows->setToolTipsVisible(true); if (plugins.empty()) { ui->menuPlugins->menuAction()->setToolTip( - tr("No plugins are installed. Check the plugins section on Cutter documentation to learn more.")); + tr("No plugins are installed. Check the plugins section on Cutter documentation to " + "learn more.")); ui->menuPlugins->setEnabled(false); } else if (ui->menuPlugins->isEmpty()) { ui->menuPlugins->menuAction()->setToolTip( @@ -255,7 +257,7 @@ void MainWindow::initUI() ui->menuPlugins->setEnabled(false); } - connect(ui->actionUnlock, &QAction::toggled, this, [this](bool unlock){ lockDocks(!unlock); }); + connect(ui->actionUnlock, &QAction::toggled, this, [this](bool unlock) { lockDocks(!unlock); }); #if QT_VERSION < QT_VERSION_CHECK(5, 7, 0) ui->actionGrouped_dock_dragging->setVisible(false); @@ -342,10 +344,10 @@ void MainWindow::initToolBar() this->visualNavbar->setMovable(false); addToolBarBreak(Qt::TopToolBarArea); addToolBar(visualNavbar); - QObject::connect(configuration, &Configuration::colorsUpdated, this, [this]() { - this->visualNavbar->updateGraphicsScene(); - }); - QObject::connect(configuration, &Configuration::interfaceThemeChanged, this, &MainWindow::chooseThemeIcons); + QObject::connect(configuration, &Configuration::colorsUpdated, this, + [this]() { this->visualNavbar->updateGraphicsScene(); }); + QObject::connect(configuration, &Configuration::interfaceThemeChanged, this, + &MainWindow::chooseThemeIcons); } void MainWindow::initDocks() @@ -356,9 +358,8 @@ void MainWindow::initDocks() overviewDock = new OverviewWidget(this); overviewDock->hide(); actionOverview = overviewDock->toggleViewAction(); - connect(overviewDock, &OverviewWidget::isAvailableChanged, this, [this](bool isAvailable) { - actionOverview->setEnabled(isAvailable); - }); + connect(overviewDock, &OverviewWidget::isAvailableChanged, this, + [this](bool isAvailable) { actionOverview->setEnabled(isAvailable); }); actionOverview->setEnabled(overviewDock->getIsAvailable()); actionOverview->setChecked(overviewDock->getUserOpened()); @@ -370,14 +371,10 @@ void MainWindow::initDocks() stringsDock = new StringsWidget(this); QList debugDocks = { - stackDock = new StackWidget(this), - threadsDock = new ThreadsWidget(this), - processesDock = new ProcessesWidget(this), - backtraceDock = new BacktraceWidget(this), - registersDock = new RegistersWidget(this), - memoryMapDock = new MemoryMapWidget(this), - breakpointDock = new BreakpointWidget(this), - registerRefsDock = new RegisterRefsWidget(this) + stackDock = new StackWidget(this), threadsDock = new ThreadsWidget(this), + processesDock = new ProcessesWidget(this), backtraceDock = new BacktraceWidget(this), + registersDock = new RegistersWidget(this), memoryMapDock = new MemoryMapWidget(this), + breakpointDock = new BreakpointWidget(this), registerRefsDock = new RegisterRefsWidget(this) }; QList infoDocks = { @@ -415,15 +412,8 @@ void MainWindow::initDocks() }; QList windowDocks = { - dashboardDock, - nullptr, - functionsDock, - overviewDock, - nullptr, - searchDock, - stringsDock, - typesDock, - nullptr, + dashboardDock, nullptr, functionsDock, overviewDock, nullptr, + searchDock, stringsDock, typesDock, nullptr, }; ui->menuWindows->insertActions(ui->actionExtraDecompiler, makeActionList(windowDocks)); QList windowDocks2 = { @@ -556,8 +546,8 @@ void MainWindow::openNewFileFailed() mb.setIcon(QMessageBox::Critical); mb.setStandardButtons(QMessageBox::Ok); mb.setWindowTitle(tr("Cannot open file!")); - mb.setText( - tr("Could not open the file! Make sure the file exists and that you have the correct permissions.")); + mb.setText(tr("Could not open the file! Make sure the file exists and that you have the " + "correct permissions.")); mb.exec(); } @@ -615,9 +605,7 @@ bool MainWindow::openProject(const QString &file) const char *s = rz_project_err_message(err); QString msg = tr("Failed to open project: %1").arg(QString::fromUtf8(s)); RzListIter *it; - CutterRListForeach(res, it, const char, s) { - msg += "\n" + QString::fromUtf8(s); - } + CutterRListForeach(res, it, const char, s) { msg += "\n" + QString::fromUtf8(s); } QMessageBox::critical(this, tr("Open Project"), msg); rz_list_free(res); return false; @@ -656,7 +644,6 @@ void MainWindow::finalizeOpen() Config()->adjustColorThemeDarkness(); setViewLayout(getViewLayout(LAYOUT_DEFAULT)); - // Set focus to disasm or graph widget // Graph with function in it has focus priority over DisasmWidget. // If there are no graph/disasm widgets focus on MainWindow @@ -730,7 +717,8 @@ void MainWindow::showProjectSaveError(RzProjectErr err) return; } const char *s = rz_project_err_message(err); - QMessageBox::critical(this, tr("Save Project"), tr("Failed to save project: %1").arg(QString::fromUtf8(s))); + QMessageBox::critical(this, tr("Save Project"), + tr("Failed to save project: %1").arg(QString::fromUtf8(s))); } void MainWindow::refreshOmniBar(const QStringList &flags) @@ -742,7 +730,7 @@ void MainWindow::setFilename(const QString &fn) { // Add file name to window title this->filename = fn; - this->setWindowTitle(APPNAME" – " + fn); + this->setWindowTitle(APPNAME " – " + fn); } void MainWindow::closeEvent(QCloseEvent *event) @@ -757,9 +745,10 @@ void MainWindow::closeEvent(QCloseEvent *event) activateWindow(); - QMessageBox::StandardButton ret = QMessageBox::question(this, APPNAME, - tr("Do you really want to exit?\nSave your project before closing!"), - (QMessageBox::StandardButtons)(QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel)); + QMessageBox::StandardButton ret = QMessageBox::question( + this, APPNAME, tr("Do you really want to exit?\nSave your project before closing!"), + (QMessageBox::StandardButtons)(QMessageBox::Save | QMessageBox::Discard + | QMessageBox::Cancel)); if (ret == QMessageBox::Cancel) { event->ignore(); return; @@ -855,12 +844,10 @@ void MainWindow::lockDocks(bool lock) } } else { for (QDockWidget *dockWidget : findChildren()) { - dockWidget->setFeatures(QDockWidget::DockWidgetClosable | - QDockWidget::DockWidgetMovable | - QDockWidget::DockWidgetFloatable); + dockWidget->setFeatures(QDockWidget::DockWidgetClosable | QDockWidget::DockWidgetMovable + | QDockWidget::DockWidgetFloatable); } } - } void MainWindow::restoreDocks() @@ -924,22 +911,15 @@ void MainWindow::restoreDocks() bool MainWindow::isDebugWidget(QDockWidget *dock) const { - return dock == stackDock || - dock == registersDock || - dock == backtraceDock || - dock == threadsDock || - dock == memoryMapDock || - dock == breakpointDock || - dock == processesDock || - dock == registerRefsDock; + return dock == stackDock || dock == registersDock || dock == backtraceDock + || dock == threadsDock || dock == memoryMapDock || dock == breakpointDock + || dock == processesDock || dock == registerRefsDock; } bool MainWindow::isExtraMemoryWidget(QDockWidget *dock) const { - return qobject_cast(dock) || - qobject_cast(dock) || - qobject_cast(dock) || - qobject_cast(dock); + return qobject_cast(dock) || qobject_cast(dock) + || qobject_cast(dock) || qobject_cast(dock); } MemoryWidgetType MainWindow::getMemoryWidgetTypeToRestore() @@ -971,7 +951,7 @@ QString MainWindow::getUniqueObjectName(const QString &widgetType) const id++; } - return widgetType + ";" + QString::number(id); + return widgetType + ";" + QString::number(id); } void MainWindow::showMemoryWidget() @@ -998,15 +978,14 @@ void MainWindow::showMemoryWidget(MemoryWidgetType type) memoryDockWidget->raiseMemoryWidget(); } -QMenu *MainWindow::createShowInMenu(QWidget *parent, RVA address, AddressTypeHint addressType) +QMenu *MainWindow::createShowInMenu(QWidget *parent, RVA address, AddressTypeHint addressType) { QMenu *menu = new QMenu(parent); // Memory dock widgets for (auto &dock : dockWidgets) { if (auto memoryWidget = qobject_cast(dock)) { if (memoryWidget->getType() == MemoryWidgetType::Graph - || memoryWidget->getType() == MemoryWidgetType::Decompiler) - { + || memoryWidget->getType() == MemoryWidgetType::Decompiler) { if (addressType == AddressTypeHint::Data) { continue; } @@ -1037,9 +1016,8 @@ QMenu *MainWindow::createShowInMenu(QWidget *parent, RVA address, AddressTypeHi menu->addSeparator(); auto createAddNewWidgetAction = [this, menu, address](QString label, MemoryWidgetType type) { QAction *action = new QAction(label, menu); - connect(action, &QAction::triggered, this, [this, address, type]() { - addNewMemoryWidget(type, address, false); - }); + connect(action, &QAction::triggered, this, + [this, address, type]() { addNewMemoryWidget(type, address, false); }); menu->addAction(action); }; createAddNewWidgetAction(tr("New disassembly"), MemoryWidgetType::Disassembly); @@ -1091,7 +1069,7 @@ MemoryDockWidget *MainWindow::addNewMemoryWidget(MemoryWidgetType type, RVA addr void MainWindow::initBackForwardMenu() { - auto prepareButtonMenu = [this](QAction *action) -> QMenu* { + auto prepareButtonMenu = [this](QAction *action) -> QMenu * { QToolButton *button = qobject_cast(ui->mainToolBar->widgetForAction(action)); if (!button) { return nullptr; @@ -1101,9 +1079,7 @@ void MainWindow::initBackForwardMenu() button->setPopupMode(QToolButton::DelayedPopup); button->setContextMenuPolicy(Qt::CustomContextMenu); connect(button, &QWidget::customContextMenuRequested, button, - [menu, button] (const QPoint &pos) { - menu->exec(button->mapToGlobal(pos)); - }); + [menu, button](const QPoint &pos) { menu->exec(button->mapToGlobal(pos)); }); QFontMetrics metrics(fontMetrics()); // Roughly 10-16 lines depending on padding size, no need to calculate more precisely @@ -1115,15 +1091,12 @@ void MainWindow::initBackForwardMenu() if (auto menu = prepareButtonMenu(ui->actionBackward)) { menu->setObjectName("historyMenu"); - connect(menu, &QMenu::aboutToShow, menu, [this, menu]() { - updateHistoryMenu(menu, false); - }); + connect(menu, &QMenu::aboutToShow, menu, + [this, menu]() { updateHistoryMenu(menu, false); }); } if (auto menu = prepareButtonMenu(ui->actionForward)) { menu->setObjectName("forwardHistoryMenu"); - connect(menu, &QMenu::aboutToShow, menu, [this, menu]() { - updateHistoryMenu(menu, true); - }); + connect(menu, &QMenu::aboutToShow, menu, [this, menu]() { updateHistoryMenu(menu, true); }); } } @@ -1147,7 +1120,8 @@ void MainWindow::updateHistoryMenu(QMenu *menu, bool redo) if (history != redo || current) { // Include current in both directions QString addressString = RAddressString(offset); - QString toolTip = QString("%1 %2").arg(addressString, name); // show non truncated name in tooltip + QString toolTip = + QString("%1 %2").arg(addressString, name); // show non truncated name in tooltip name.truncate(MAX_NAME_LENGTH); // TODO:#1904 use common name shortening function QString label = QString("%1 (%2)").arg(name, addressString); @@ -1186,7 +1160,6 @@ void MainWindow::updateHistoryMenu(QMenu *menu, bool redo) } ++steps; } - } void MainWindow::updateLayoutsMenu() @@ -1198,9 +1171,8 @@ void MainWindow::updateLayoutsMenu() continue; } auto action = new QAction(it.key(), ui->menuLayouts); - connect(action, &QAction::triggered, this, [this, name]() { - setViewLayout(getViewLayout(name)); - }); + connect(action, &QAction::triggered, this, + [this, name]() { setViewLayout(getViewLayout(name)); }); ui->menuLayouts->addAction(action); } } @@ -1214,9 +1186,11 @@ void MainWindow::saveNamedLayout() names.removeAll(LAYOUT_DEFAULT); while (name.isEmpty() || isBuiltinLayoutName(name)) { if (ok) { - QMessageBox::warning(this, tr("Save layout error"), tr("'%1' is not a valid name.").arg(name)); + QMessageBox::warning(this, tr("Save layout error"), + tr("'%1' is not a valid name.").arg(name)); } - name = QInputDialog::getItem(this, tr("Save layout"), tr("Enter name"), names, -1, true, &ok); + name = QInputDialog::getItem(this, tr("Save layout"), tr("Enter name"), names, -1, true, + &ok); if (!ok) { return; } @@ -1261,17 +1235,12 @@ void MainWindow::removeWidget(CutterDockWidget *widget) void MainWindow::showZenDocks() { - const QList zenDocks = { functionsDock, - dashboardDock, - stringsDock, - searchDock, - importsDock - }; + const QList zenDocks = { functionsDock, dashboardDock, stringsDock, searchDock, + importsDock }; functionDockWidthToRestore = functionsDock->maximumWidth(); functionsDock->setMaximumWidth(200); for (auto w : dockWidgets) { - if (zenDocks.contains(w) || - isExtraMemoryWidget(w)) { + if (zenDocks.contains(w) || isExtraMemoryWidget(w)) { w->show(); } } @@ -1280,27 +1249,19 @@ void MainWindow::showZenDocks() void MainWindow::showDebugDocks() { - const QList debugDocks = { functionsDock, - stringsDock, - searchDock, - stackDock, - registersDock, - backtraceDock, - threadsDock, - memoryMapDock, - breakpointDock - }; + const QList debugDocks = { functionsDock, stringsDock, searchDock, + stackDock, registersDock, backtraceDock, + threadsDock, memoryMapDock, breakpointDock }; functionDockWidthToRestore = functionsDock->maximumWidth(); functionsDock->setMaximumWidth(200); auto registerWidth = qhelpers::forceWidth(registersDock, std::min(500, this->width() / 4)); auto registerHeight = qhelpers::forceHeight(registersDock, std::max(100, height() / 2)); QDockWidget *widgetToFocus = nullptr; for (auto w : dockWidgets) { - if (debugDocks.contains(w) || - isExtraMemoryWidget(w)) { + if (debugDocks.contains(w) || isExtraMemoryWidget(w)) { w->show(); } - if (qobject_cast(w)) { + if (qobject_cast(w)) { widgetToFocus = w; } } @@ -1313,12 +1274,12 @@ void MainWindow::showDebugDocks() void MainWindow::dockOnMainArea(QDockWidget *widget) { - QDockWidget* best = nullptr; + QDockWidget *best = nullptr; float bestScore = 1; // choose best existing area for placing the new widget for (auto dock : dockWidgets) { - if (dock->isHidden() || dock == widget || - dock->isFloating() || // tabifying onto floating dock using code doesn't work well + if (dock->isHidden() || dock == widget || dock->isFloating() + || // tabifying onto floating dock using code doesn't work well dock->parentWidget() != this) { // floating group isn't considered floating continue; } @@ -1392,19 +1353,16 @@ void MainWindow::setViewLayout(const CutterLayout &layout) QStringList docksToCreate; if (isDefault) { - docksToCreate = QStringList { - DisassemblyWidget::getWidgetType(), - GraphWidget::getWidgetType(), - HexdumpWidget::getWidgetType(), - DecompilerWidget::getWidgetType() - }; + docksToCreate = + QStringList { DisassemblyWidget::getWidgetType(), GraphWidget::getWidgetType(), + HexdumpWidget::getWidgetType(), DecompilerWidget::getWidgetType() }; } else { docksToCreate = layout.viewProperties.keys(); } for (const auto &it : docksToCreate) { if (std::none_of(dockWidgets.constBegin(), dockWidgets.constEnd(), - [&it](QDockWidget * w) { return w->objectName() == it; })) { + [&it](QDockWidget *w) { return w->objectName() == it; })) { auto className = it.split(';').at(0); if (widgetTypeToConstructorMap.contains(className)) { auto widget = widgetTypeToConstructorMap[className](this); @@ -1490,7 +1448,8 @@ void MainWindow::saveLayouts(QSettings &settings) settings.setValue("state", layout.state); settings.setValue("geometry", layout.geometry); QVariantMap properties; - for (auto it = layout.viewProperties.begin(), end = layout.viewProperties.end(); it != end; ++it) { + for (auto it = layout.viewProperties.begin(), end = layout.viewProperties.end(); it != end; + ++it) { properties.insert(it.key(), it.value()); } settings.setValue("docks", properties); @@ -1498,7 +1457,6 @@ void MainWindow::saveLayouts(QSettings &settings) settings.endArray(); } - void MainWindow::on_actionDefault_triggered() { if (core->currentlyDebugging) { @@ -1510,7 +1468,6 @@ void MainWindow::on_actionDefault_triggered() } } - /** * @brief MainWindow::on_actionNew_triggered * Open a new Cutter session. @@ -1518,7 +1475,7 @@ void MainWindow::on_actionDefault_triggered() void MainWindow::on_actionNew_triggered() { // Create a new Cutter process - static_cast(qApp)->launchNewInstance(); + static_cast(qApp)->launchNewInstance(); } void MainWindow::on_actionSave_triggered() @@ -1538,8 +1495,8 @@ void MainWindow::on_actionRun_Script_triggered() dialog.setViewMode(QFileDialog::Detail); dialog.setDirectory(QDir::home()); - const QString &fileName = QDir::toNativeSeparators(dialog.getOpenFileName(this, - tr("Select Rizin script"))); + const QString &fileName = + QDir::toNativeSeparators(dialog.getOpenFileName(this, tr("Select Rizin script"))); if (fileName.isEmpty()) // Cancel was pressed return; @@ -1581,10 +1538,9 @@ void MainWindow::on_actionTabs_on_Top_triggered() void MainWindow::on_actionReset_settings_triggered() { - QMessageBox::StandardButton ret = - (QMessageBox::StandardButton)QMessageBox::question(this, APPNAME, - tr("Do you really want to clear all settings?"), - QMessageBox::Ok | QMessageBox::Cancel); + QMessageBox::StandardButton ret = (QMessageBox::StandardButton)QMessageBox::question( + this, APPNAME, tr("Do you really want to clear all settings?"), + QMessageBox::Ok | QMessageBox::Cancel); if (ret == QMessageBox::Ok) { Config()->resetAll(); readSettings(); @@ -1620,7 +1576,7 @@ void MainWindow::on_actionRefresh_contents_triggered() void MainWindow::on_actionPreferences_triggered() { - if (!findChild()) { + if (!findChild()) { auto dialog = new PreferencesDialog(this); dialog->show(); } @@ -1661,7 +1617,7 @@ void MainWindow::on_actionAnalyze_triggered() { auto *analTask = new AnalTask(); InitialOptions options; - options.analCmd = { {"aaa", "Auto analysis"} }; + options.analCmd = { { "aaa", "Auto analysis" } }; analTask->setOptions(options); AsyncTask::Ptr analTaskPtr(analTask); @@ -1810,13 +1766,13 @@ bool MainWindow::eventFilter(QObject *, QEvent *event) bool MainWindow::event(QEvent *event) { - if (event->type() == QEvent::FontChange - || event->type() == QEvent::StyleChange + if (event->type() == QEvent::FontChange || event->type() == QEvent::StyleChange || event->type() == QEvent::PaletteChange) { -#if QT_VERSION < QT_VERSION_CHECK(5,10,0) +#if QT_VERSION < QT_VERSION_CHECK(5, 10, 0) QMetaObject::invokeMethod(Config(), "refreshFont", Qt::ConnectionType::QueuedConnection); #else - QMetaObject::invokeMethod(Config(), &Configuration::refreshFont, Qt::ConnectionType::QueuedConnection); + QMetaObject::invokeMethod(Config(), &Configuration::refreshFont, + Qt::ConnectionType::QueuedConnection); #endif } return QMainWindow::event(event); @@ -1843,31 +1799,30 @@ void MainWindow::messageBoxWarning(QString title, QString message) void MainWindow::chooseThemeIcons() { // List of QActions which have alternative icons in different themes - const QList> kSupportedIconsNames { + const QList> kSupportedIconsNames { { ui->actionForward, QStringLiteral("arrow_right.svg") }, - { ui->actionBackward, QStringLiteral("arrow_left.svg") }, + { ui->actionBackward, QStringLiteral("arrow_left.svg") }, }; - // Set the correct icon for the QAction qhelpers::setThemeIcons(kSupportedIconsNames, [](void *obj, const QIcon &icon) { - static_cast(obj)->setIcon(icon); + static_cast(obj)->setIcon(icon); }); } void MainWindow::onZoomIn() { - Config()->setZoomFactor(Config()->getZoomFactor() + 0.1); + Config()->setZoomFactor(Config()->getZoomFactor() + 0.1); } void MainWindow::onZoomOut() { - Config()->setZoomFactor(Config()->getZoomFactor() - 0.1); + Config()->setZoomFactor(Config()->getZoomFactor() - 0.1); } void MainWindow::onZoomReset() { - Config()->setZoomFactor(1.0); + Config()->setZoomFactor(1.0); } QMenu *MainWindow::getContextMenuExtensions(ContextMenuType type) diff --git a/src/core/MainWindow.h b/src/core/MainWindow.h index dac4e575..bd73c1df 100644 --- a/src/core/MainWindow.h +++ b/src/core/MainWindow.h @@ -90,10 +90,14 @@ public: void addMemoryDockWidget(MemoryDockWidget *widget); void removeWidget(CutterDockWidget *widget); void addExtraWidget(CutterDockWidget *extraDock); - MemoryDockWidget *addNewMemoryWidget(MemoryWidgetType type, RVA address, bool synchronized = true); + MemoryDockWidget *addNewMemoryWidget(MemoryWidgetType type, RVA address, + bool synchronized = true); CUTTER_DEPRECATED("Action will be ignored. Use addPluginDockWidget(CutterDockWidget*) instead.") - void addPluginDockWidget(CutterDockWidget *dockWidget, QAction *) { addPluginDockWidget(dockWidget); } + void addPluginDockWidget(CutterDockWidget *dockWidget, QAction *) + { + addPluginDockWidget(dockWidget); + } void addPluginDockWidget(CutterDockWidget *dockWidget); enum class MenuType { File, Edit, View, Windows, Debug, Help, Plugins }; /** @@ -104,19 +108,17 @@ public: QMenu *getMenuByType(MenuType type); void addMenuFileAction(QAction *action); - QString getFilename() const - { - return filename; - } + QString getFilename() const { return filename; } void messageBoxWarning(QString title, QString message); QString getUniqueObjectName(const QString &widgetType) const; void showMemoryWidget(); void showMemoryWidget(MemoryWidgetType type); enum class AddressTypeHint { Function, Data, Unknown }; - QMenu *createShowInMenu(QWidget *parent, RVA address, AddressTypeHint addressType = AddressTypeHint::Unknown); - void setCurrentMemoryWidget(MemoryDockWidget* memoryWidget); - MemoryDockWidget* getLastMemoryWidget(); + QMenu *createShowInMenu(QWidget *parent, RVA address, + AddressTypeHint addressType = AddressTypeHint::Unknown); + void setCurrentMemoryWidget(MemoryDockWidget *memoryWidget); + MemoryDockWidget *getLastMemoryWidget(); /* Context menu plugins */ enum class ContextMenuType { Disassembly, Addressable }; @@ -202,6 +204,7 @@ private slots: void onZoomReset(); void setAvailableIOModeOptions(); + private: CutterCore *core; @@ -221,41 +224,41 @@ private: QList dockWidgets; QList pluginDocks; - OverviewWidget *overviewDock = nullptr; + OverviewWidget *overviewDock = nullptr; QAction *actionOverview = nullptr; - EntrypointWidget *entrypointDock = nullptr; - FunctionsWidget *functionsDock = nullptr; - ImportsWidget *importsDock = nullptr; - ExportsWidget *exportsDock = nullptr; - HeadersWidget *headersDock = nullptr; - TypesWidget *typesDock = nullptr; - SearchWidget *searchDock = nullptr; - SymbolsWidget *symbolsDock = nullptr; - RelocsWidget *relocsDock = nullptr; - CommentsWidget *commentsDock = nullptr; - StringsWidget *stringsDock = nullptr; - FlagsWidget *flagsDock = nullptr; - Dashboard *dashboardDock = nullptr; - SdbWidget *sdbDock = nullptr; - SectionsWidget *sectionsDock = nullptr; - SegmentsWidget *segmentsDock = nullptr; - ZignaturesWidget *zignaturesDock = nullptr; - ConsoleWidget *consoleDock = nullptr; - ClassesWidget *classesDock = nullptr; - ResourcesWidget *resourcesDock = nullptr; - VTablesWidget *vTablesDock = nullptr; - CutterDockWidget *stackDock = nullptr; - CutterDockWidget *threadsDock = nullptr; - CutterDockWidget *processesDock = nullptr; - CutterDockWidget *registersDock = nullptr; - CutterDockWidget *backtraceDock = nullptr; - CutterDockWidget *memoryMapDock = nullptr; - NewFileDialog *newFileDialog = nullptr; - CutterDockWidget *breakpointDock = nullptr; - CutterDockWidget *registerRefsDock = nullptr; - RizinGraphWidget *rzGraphDock = nullptr; - CallGraphWidget *callGraphDock = nullptr; - CallGraphWidget *globalCallGraphDock = nullptr; + EntrypointWidget *entrypointDock = nullptr; + FunctionsWidget *functionsDock = nullptr; + ImportsWidget *importsDock = nullptr; + ExportsWidget *exportsDock = nullptr; + HeadersWidget *headersDock = nullptr; + TypesWidget *typesDock = nullptr; + SearchWidget *searchDock = nullptr; + SymbolsWidget *symbolsDock = nullptr; + RelocsWidget *relocsDock = nullptr; + CommentsWidget *commentsDock = nullptr; + StringsWidget *stringsDock = nullptr; + FlagsWidget *flagsDock = nullptr; + Dashboard *dashboardDock = nullptr; + SdbWidget *sdbDock = nullptr; + SectionsWidget *sectionsDock = nullptr; + SegmentsWidget *segmentsDock = nullptr; + ZignaturesWidget *zignaturesDock = nullptr; + ConsoleWidget *consoleDock = nullptr; + ClassesWidget *classesDock = nullptr; + ResourcesWidget *resourcesDock = nullptr; + VTablesWidget *vTablesDock = nullptr; + CutterDockWidget *stackDock = nullptr; + CutterDockWidget *threadsDock = nullptr; + CutterDockWidget *processesDock = nullptr; + CutterDockWidget *registersDock = nullptr; + CutterDockWidget *backtraceDock = nullptr; + CutterDockWidget *memoryMapDock = nullptr; + NewFileDialog *newFileDialog = nullptr; + CutterDockWidget *breakpointDock = nullptr; + CutterDockWidget *registerRefsDock = nullptr; + RizinGraphWidget *rzGraphDock = nullptr; + CallGraphWidget *callGraphDock = nullptr; + CallGraphWidget *globalCallGraphDock = nullptr; QMenu *disassemblyContextMenuExtensions = nullptr; QMenu *addressableContextMenuExtensions = nullptr; @@ -266,7 +269,8 @@ private: void initToolBar(); void initDocks(); void initBackForwardMenu(); - void displayInitialOptionsDialog(const InitialOptions &options = InitialOptions(), bool skipOptionsDialog = false); + void displayInitialOptionsDialog(const InitialOptions &options = InitialOptions(), + bool skipOptionsDialog = false); Cutter::CutterLayout getViewLayout(); Cutter::CutterLayout getViewLayout(const QString &name); @@ -275,7 +279,6 @@ private: void loadLayouts(QSettings &settings); void saveLayouts(QSettings &settings); - void updateMemberPointers(); void restoreDocks(); void showZenDocks(); @@ -309,12 +312,13 @@ private: MemoryWidgetType getMemoryWidgetTypeToRestore(); /** - * @brief Map from a widget type (e.g. DisassemblyWidget::getWidgetType()) to the respective contructor of the widget + * @brief Map from a widget type (e.g. DisassemblyWidget::getWidgetType()) to the respective + * contructor of the widget */ - QMap> widgetTypeToConstructorMap; + QMap> widgetTypeToConstructorMap; - MemoryDockWidget* lastSyncMemoryWidget = nullptr; - MemoryDockWidget* lastMemoryWidget = nullptr; + MemoryDockWidget *lastSyncMemoryWidget = nullptr; + MemoryDockWidget *lastMemoryWidget = nullptr; int functionDockWidthToRestore = 0; }; diff --git a/src/dialogs/AboutDialog.cpp b/src/dialogs/AboutDialog.cpp index 9e1b7756..49a3ff5c 100644 --- a/src/dialogs/AboutDialog.cpp +++ b/src/dialogs/AboutDialog.cpp @@ -18,37 +18,39 @@ #include "CutterConfig.h" -AboutDialog::AboutDialog(QWidget *parent) : - QDialog(parent), - ui(new Ui::AboutDialog) +AboutDialog::AboutDialog(QWidget *parent) : QDialog(parent), ui(new Ui::AboutDialog) { ui->setupUi(this); setWindowFlags(windowFlags() & (~Qt::WindowContextHelpButtonHint)); ui->logoSvgWidget->load(Config()->getLogoFile()); - QString aboutString(tr("Version") + " " CUTTER_VERSION_FULL "
" - + tr("Using rizin-") + RZ_GITTAP + "
" - + buildQtVersionString() - + "

" + tr("Optional Features:") + "
" - + QString("Python: %1
").arg( + QString aboutString( + tr("Version") + " " CUTTER_VERSION_FULL "
" + tr("Using rizin-") + RZ_GITTAP + + "
" + buildQtVersionString() + "

" + tr("Optional Features:") + "
" + + QString("Python: %1
") + .arg( #ifdef CUTTER_ENABLE_PYTHON - "ON" + "ON" #else - "OFF" + "OFF" #endif - ) - + QString("Python Bindings: %2

").arg( + ) + + QString("Python Bindings: %2

") + .arg( #ifdef CUTTER_ENABLE_PYTHON_BINDINGS - "ON" + "ON" #else - "OFF" + "OFF" #endif - ) - + "

" + tr("License") + "

" - + tr("This Software is released under the GNU General Public License v3.0") - + "

" + tr("Authors") + "

" - + tr("Cutter is developed by the community and maintained by its core and development teams.
") - + tr("Check our contributors page for the full list of contributors.")); + ) + + "

" + tr("License") + "

" + + tr("This Software is released under the GNU General Public License v3.0") + "

" + + tr("Authors") + "

" + + tr("Cutter is developed by the community and maintained by its core and development " + "teams.
") + + tr("Check our contributors " + "page for the full list of contributors.")); ui->label->setText(aboutString); QSignalBlocker s(ui->updatesCheckBox); @@ -97,17 +99,18 @@ void AboutDialog::on_checkForUpdatesButton_clicked() connect(&updateWorker, &UpdateWorker::checkComplete, &waitDialog, &QProgressDialog::cancel); connect(&updateWorker, &UpdateWorker::checkComplete, - [&updateWorker](const QVersionNumber & version, const QString & error) { - if (!error.isEmpty()) { - QMessageBox::critical(nullptr, tr("Error!"), error); - } else { - if (version <= UpdateWorker::currentVersionNumber()) { - QMessageBox::information(nullptr, tr("Version control"), tr("Cutter is up to date!")); - } else { - updateWorker.showUpdateDialog(false); - } - } - }); + [&updateWorker](const QVersionNumber &version, const QString &error) { + if (!error.isEmpty()) { + QMessageBox::critical(nullptr, tr("Error!"), error); + } else { + if (version <= UpdateWorker::currentVersionNumber()) { + QMessageBox::information(nullptr, tr("Version control"), + tr("Cutter is up to date!")); + } else { + updateWorker.showUpdateDialog(false); + } + } + }); updateWorker.checkCurrentVersion(7000); waitDialog.exec(); @@ -123,13 +126,13 @@ static QString compilerString() { #if defined(Q_CC_CLANG) // must be before GNU, because clang claims to be GNU too QString isAppleString; -#if defined(__apple_build_version__) // Apple clang has other version numbers +# if defined(__apple_build_version__) // Apple clang has other version numbers isAppleString = QLatin1String(" (Apple)"); -#endif - return QLatin1String("Clang " ) + QString::number(__clang_major__) + QLatin1Char('.') - + QString::number(__clang_minor__) + isAppleString; +# endif + return QLatin1String("Clang ") + QString::number(__clang_major__) + QLatin1Char('.') + + QString::number(__clang_minor__) + isAppleString; #elif defined(Q_CC_GNU) - return QLatin1String("GCC " ) + QLatin1String(__VERSION__); + return QLatin1String("GCC ") + QLatin1String(__VERSION__); #elif defined(Q_CC_MSVC) if (_MSC_VER > 1999) return QLatin1String("MSVC "); @@ -143,7 +146,6 @@ static QString compilerString() QString AboutDialog::buildQtVersionString(void) { - return tr("Based on Qt %1 (%2, %3 bit)").arg(QLatin1String(qVersion()), - compilerString(), - QString::number(QSysInfo::WordSize)); + return tr("Based on Qt %1 (%2, %3 bit)") + .arg(QLatin1String(qVersion()), compilerString(), QString::number(QSysInfo::WordSize)); } diff --git a/src/dialogs/AboutDialog.h b/src/dialogs/AboutDialog.h index 15a458bd..2d3ae342 100644 --- a/src/dialogs/AboutDialog.h +++ b/src/dialogs/AboutDialog.h @@ -26,14 +26,14 @@ private slots: * @fn AboutDialog::on_checkForUpdatesButton_clicked() * * @brief Initiates process of checking for updates. - */ + */ void on_checkForUpdatesButton_clicked(); /** * @fn AboutDialog::on_updatesCheckBox_stateChanged(int state) * * @brief Changes value of autoUpdateEnabled option in settings. - */ + */ void on_updatesCheckBox_stateChanged(int state); private: diff --git a/src/dialogs/AsyncTaskDialog.cpp b/src/dialogs/AsyncTaskDialog.cpp index 2a7c3475..33507b91 100644 --- a/src/dialogs/AsyncTaskDialog.cpp +++ b/src/dialogs/AsyncTaskDialog.cpp @@ -4,11 +4,8 @@ #include "ui_AsyncTaskDialog.h" - AsyncTaskDialog::AsyncTaskDialog(AsyncTask::Ptr task, QWidget *parent) - : QDialog(parent), - ui(new Ui::AsyncTaskDialog), - task(task) + : QDialog(parent), ui(new Ui::AsyncTaskDialog), task(task) { ui->setupUi(this); @@ -18,9 +15,7 @@ AsyncTaskDialog::AsyncTaskDialog(AsyncTask::Ptr task, QWidget *parent) } connect(task.data(), &AsyncTask::logChanged, this, &AsyncTaskDialog::updateLog); - connect(task.data(), &AsyncTask::finished, this, [this]() { - close(); - }); + connect(task.data(), &AsyncTask::finished, this, [this]() { close(); }); updateLog(task->getLog()); @@ -32,9 +27,7 @@ AsyncTaskDialog::AsyncTaskDialog(AsyncTask::Ptr task, QWidget *parent) updateProgressTimer(); } -AsyncTaskDialog::~AsyncTaskDialog() -{ -} +AsyncTaskDialog::~AsyncTaskDialog() {} void AsyncTaskDialog::updateLog(const QString &log) { diff --git a/src/dialogs/AsyncTaskDialog.h b/src/dialogs/AsyncTaskDialog.h index 855f9b1a..08431c71 100644 --- a/src/dialogs/AsyncTaskDialog.h +++ b/src/dialogs/AsyncTaskDialog.h @@ -21,8 +21,8 @@ public: AsyncTaskDialog(AsyncTask::Ptr task, QWidget *parent = nullptr); ~AsyncTaskDialog(); - void setInterruptOnClose(bool v) { interruptOnClose = v; } - bool getInterruptOnClose() { return interruptOnClose; } + void setInterruptOnClose(bool v) { interruptOnClose = v; } + bool getInterruptOnClose() { return interruptOnClose; } public slots: void reject() override; @@ -42,4 +42,4 @@ private: bool interruptOnClose = false; }; -#endif //ASYNCTASKDIALOG_H +#endif // ASYNCTASKDIALOG_H diff --git a/src/dialogs/AttachProcDialog.cpp b/src/dialogs/AttachProcDialog.cpp index e2f04bff..d2e8f42e 100644 --- a/src/dialogs/AttachProcDialog.cpp +++ b/src/dialogs/AttachProcDialog.cpp @@ -10,8 +10,7 @@ // ------------ // ProcessModel // ------------ -ProcessModel::ProcessModel(QObject *parent) - : QAbstractListModel(parent) +ProcessModel::ProcessModel(QObject *parent) : QAbstractListModel(parent) { updateData(); } @@ -125,7 +124,8 @@ QString ProcessBeingAnalysedProxyModel::processPathToFilename(const QString &pat bool ProcessBeingAnalysedProxyModel::filterAcceptsRow(int row, const QModelIndex &parent) const { QModelIndex index = sourceModel()->index(row, 0, parent); - ProcessDescription item = index.data(ProcessModel::ProcDescriptionRole).value(); + ProcessDescription item = + index.data(ProcessModel::ProcDescriptionRole).value(); QString procFilename = processPathToFilename(item.path); return procFilename == processBeingAnalysedFilename; @@ -134,10 +134,10 @@ bool ProcessBeingAnalysedProxyModel::filterAcceptsRow(int row, const QModelIndex bool ProcessBeingAnalysedProxyModel::lessThan(const QModelIndex &left, const QModelIndex &right) const { - ProcessDescription leftProc = left.data( - ProcessModel::ProcDescriptionRole).value(); - ProcessDescription rightProc = right.data( - ProcessModel::ProcDescriptionRole).value(); + ProcessDescription leftProc = + left.data(ProcessModel::ProcDescriptionRole).value(); + ProcessDescription rightProc = + right.data(ProcessModel::ProcDescriptionRole).value(); return ProcessModel::lessThan(leftProc, rightProc, left.column()); } @@ -154,16 +154,17 @@ ProcessProxyModel::ProcessProxyModel(ProcessModel *sourceModel, QObject *parent) bool ProcessProxyModel::filterAcceptsRow(int row, const QModelIndex &parent) const { QModelIndex index = sourceModel()->index(row, 0, parent); - ProcessDescription item = index.data(ProcessModel::ProcDescriptionRole).value(); + ProcessDescription item = + index.data(ProcessModel::ProcDescriptionRole).value(); return item.path.contains(filterRegExp()); } bool ProcessProxyModel::lessThan(const QModelIndex &left, const QModelIndex &right) const { - ProcessDescription leftProc = left.data( - ProcessModel::ProcDescriptionRole).value(); - ProcessDescription rightProc = right.data( - ProcessModel::ProcDescriptionRole).value(); + ProcessDescription leftProc = + left.data(ProcessModel::ProcDescriptionRole).value(); + ProcessDescription rightProc = + right.data(ProcessModel::ProcDescriptionRole).value(); return ProcessModel::lessThan(leftProc, rightProc, left.column()); } @@ -171,9 +172,7 @@ bool ProcessProxyModel::lessThan(const QModelIndex &left, const QModelIndex &rig // ---------------- // AttachProcDialog // ---------------- -AttachProcDialog::AttachProcDialog(QWidget *parent) : - QDialog(parent), - ui(new Ui::AttachProcDialog) +AttachProcDialog::AttachProcDialog(QWidget *parent) : QDialog(parent), ui(new Ui::AttachProcDialog) { ui->setupUi(this); setWindowFlags(windowFlags() & (~Qt::WindowContextHelpButtonHint)); @@ -232,13 +231,19 @@ void AttachProcDialog::updateModelData() if (allViewHadSelection) { allViewPrevScrollPos = allView->verticalScrollBar()->value(); - allViewPrevPID = allView->selectionModel()->currentIndex().data( - ProcessModel::ProcDescriptionRole).value().pid; + allViewPrevPID = allView->selectionModel() + ->currentIndex() + .data(ProcessModel::ProcDescriptionRole) + .value() + .pid; } if (smallViewHadSelection) { smallViewPrevScrollPos = smallView->verticalScrollBar()->value(); - smallViewPrevPID = smallView->selectionModel()->currentIndex().data( - ProcessModel::ProcDescriptionRole).value().pid; + smallViewPrevPID = smallView->selectionModel() + ->currentIndex() + .data(ProcessModel::ProcDescriptionRole) + .value() + .pid; } // Let the model update @@ -246,16 +251,18 @@ void AttachProcDialog::updateModelData() // Restore the selection and scroll position if (allViewHadSelection) { - QModelIndexList idx = allView->model()->match( - allView->model()->index(0, 0), Qt::DisplayRole, QVariant::fromValue(allViewPrevPID)); + QModelIndexList idx = + allView->model()->match(allView->model()->index(0, 0), Qt::DisplayRole, + QVariant::fromValue(allViewPrevPID)); if (!idx.isEmpty()) { allView->setCurrentIndex(idx.first()); allView->verticalScrollBar()->setValue(allViewPrevScrollPos); } } if (smallViewHadSelection) { - QModelIndexList idx = smallView->model()->match( - smallView->model()->index(0, 0), Qt::DisplayRole, QVariant::fromValue(smallViewPrevPID)); + QModelIndexList idx = + smallView->model()->match(smallView->model()->index(0, 0), Qt::DisplayRole, + QVariant::fromValue(smallViewPrevPID)); if (!idx.isEmpty()) { smallView->setCurrentIndex(idx.first()); @@ -265,14 +272,13 @@ void AttachProcDialog::updateModelData() // Init selection if nothing was ever selected yet, and a new process with the same name // as the one being analysed was launched. - if (!allView->selectionModel()->hasSelection() && !smallView->selectionModel()->hasSelection()) { + if (!allView->selectionModel()->hasSelection() + && !smallView->selectionModel()->hasSelection()) { smallView->setCurrentIndex(smallView->model()->index(0, 0)); } } -void AttachProcDialog::on_buttonBox_accepted() -{ -} +void AttachProcDialog::on_buttonBox_accepted() {} void AttachProcDialog::on_buttonBox_rejected() { @@ -302,12 +308,18 @@ int AttachProcDialog::getPID() // Here we need to know which table was selected last to get the proper PID if (wasAllProcViewLastPressed && ui->allProcView->selectionModel()->hasSelection()) { - pid = ui->allProcView->selectionModel()->currentIndex(). - data(ProcessModel::ProcDescriptionRole).value().pid; + pid = ui->allProcView->selectionModel() + ->currentIndex() + .data(ProcessModel::ProcDescriptionRole) + .value() + .pid; } else if (!wasAllProcViewLastPressed && ui->procBeingAnalyzedView->selectionModel()->hasSelection()) { - pid = ui->procBeingAnalyzedView->selectionModel()->currentIndex(). - data(ProcessModel::ProcDescriptionRole).value().pid; + pid = ui->procBeingAnalyzedView->selectionModel() + ->currentIndex() + .data(ProcessModel::ProcDescriptionRole) + .value() + .pid; } else { // Error attaching. No process selected! Happens when you press ENTER but // there was no process with the same name as the one being analyzed. diff --git a/src/dialogs/AttachProcDialog.h b/src/dialogs/AttachProcDialog.h index d2132a35..6f60d459 100644 --- a/src/dialogs/AttachProcDialog.h +++ b/src/dialogs/AttachProcDialog.h @@ -15,8 +15,7 @@ class MainWindow; class QTreeWidget; class QTreeWidgetItem; - -class ProcessModel: public QAbstractListModel +class ProcessModel : public QAbstractListModel { Q_OBJECT @@ -34,14 +33,13 @@ public: QVariant data(const QModelIndex &index, int role) const; QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const; - static bool lessThan(const ProcessDescription &left, const ProcessDescription &right, int column); + static bool lessThan(const ProcessDescription &left, const ProcessDescription &right, + int column); public slots: void updateData(); }; - - class ProcessProxyModel : public QSortFilterProxyModel { Q_OBJECT @@ -54,7 +52,6 @@ protected: bool lessThan(const QModelIndex &left, const QModelIndex &right) const override; }; - class ProcessBeingAnalysedProxyModel : public QSortFilterProxyModel { Q_OBJECT @@ -71,8 +68,6 @@ private: QString processPathToFilename(const QString &path) const; }; - - class AttachProcDialog : public QDialog { Q_OBJECT diff --git a/src/dialogs/BreakpointsDialog.cpp b/src/dialogs/BreakpointsDialog.cpp index 2a0fa98d..979039df 100644 --- a/src/dialogs/BreakpointsDialog.cpp +++ b/src/dialogs/BreakpointsDialog.cpp @@ -7,15 +7,14 @@ #include #include -BreakpointsDialog::BreakpointsDialog(bool editMode, QWidget *parent) : - QDialog(parent), - ui(new Ui::BreakpointsDialog), - editMode(editMode) +BreakpointsDialog::BreakpointsDialog(bool editMode, QWidget *parent) + : QDialog(parent), ui(new Ui::BreakpointsDialog), editMode(editMode) { ui->setupUi(this); setWindowFlags(windowFlags() & (~Qt::WindowContextHelpButtonHint)); - connect(ui->breakpointPosition, &QLineEdit::textChanged, this, &BreakpointsDialog::refreshOkButton); + connect(ui->breakpointPosition, &QLineEdit::textChanged, this, + &BreakpointsDialog::refreshOkButton); refreshOkButton(); if (editMode) { @@ -24,15 +23,16 @@ BreakpointsDialog::BreakpointsDialog(bool editMode, QWidget *parent) : setWindowTitle(tr("New breakpoint")); } - - struct { + struct + { QString label; QString tooltip; BreakpointDescription::PositionType type; } positionTypes[] = { - {tr("Address"), tr("Address or expression calculated when creating breakpoint"), BreakpointDescription::Address}, - {tr("Named"), tr("Expression - stored as expression"), BreakpointDescription::Named}, - {tr("Module offset"), tr("Offset relative to module"), BreakpointDescription::Module}, + { tr("Address"), tr("Address or expression calculated when creating breakpoint"), + BreakpointDescription::Address }, + { tr("Named"), tr("Expression - stored as expression"), BreakpointDescription::Named }, + { tr("Module offset"), tr("Offset relative to module"), BreakpointDescription::Module }, }; int index = 0; for (auto &item : positionTypes) { @@ -41,8 +41,9 @@ BreakpointsDialog::BreakpointsDialog(bool editMode, QWidget *parent) : index++; } - connect(ui->positionType, static_cast(&QComboBox::currentIndexChanged), - this, &BreakpointsDialog::onTypeChanged); + connect(ui->positionType, + static_cast(&QComboBox::currentIndexChanged), this, + &BreakpointsDialog::onTypeChanged); onTypeChanged(); auto modules = Core()->getMemoryMap(); @@ -50,7 +51,7 @@ BreakpointsDialog::BreakpointsDialog(bool editMode, QWidget *parent) : for (const auto &module : modules) { moduleNames.insert(module.fileName); } - for (const auto& module : moduleNames) { + for (const auto &module : moduleNames) { ui->moduleName->addItem(module); } ui->moduleName->setCurrentText(""); @@ -111,7 +112,8 @@ BreakpointsDialog::~BreakpointsDialog() {} BreakpointDescription BreakpointsDialog::getDescription() { BreakpointDescription breakpoint; - auto positionType = ui->positionType->currentData().value(); + auto positionType = + ui->positionType->currentData().value(); switch (positionType) { case BreakpointDescription::Address: breakpoint.addr = Core()->math(ui->breakpointPosition->text()); @@ -167,7 +169,8 @@ void BreakpointsDialog::onTypeChanged() bool moduleEnabled = ui->positionType->currentData() == QVariant(BreakpointDescription::Module); ui->moduleLabel->setEnabled(moduleEnabled); ui->moduleName->setEnabled(moduleEnabled); - ui->breakpointPosition->setPlaceholderText(ui->positionType->currentData(Qt::ToolTipRole).toString()); + ui->breakpointPosition->setPlaceholderText( + ui->positionType->currentData(Qt::ToolTipRole).toString()); } void BreakpointsDialog::configureCheckboxRestrictions() diff --git a/src/dialogs/BreakpointsDialog.h b/src/dialogs/BreakpointsDialog.h index 2c3e6d64..6b267b56 100644 --- a/src/dialogs/BreakpointsDialog.h +++ b/src/dialogs/BreakpointsDialog.h @@ -21,7 +21,8 @@ public: BreakpointDescription getDescription(); static void createNewBreakpoint(RVA address = RVA_INVALID, QWidget *parent = nullptr); - static void editBreakpoint(const BreakpointDescription& breakpoint, QWidget *parent = nullptr); + static void editBreakpoint(const BreakpointDescription &breakpoint, QWidget *parent = nullptr); + private: std::unique_ptr ui; bool editMode = false; diff --git a/src/dialogs/CommentsDialog.cpp b/src/dialogs/CommentsDialog.cpp index fb724611..b534fbfb 100644 --- a/src/dialogs/CommentsDialog.cpp +++ b/src/dialogs/CommentsDialog.cpp @@ -3,9 +3,7 @@ #include "core/Cutter.h" -CommentsDialog::CommentsDialog(QWidget *parent) : - QDialog(parent), - ui(new Ui::CommentsDialog) +CommentsDialog::CommentsDialog(QWidget *parent) : QDialog(parent), ui(new Ui::CommentsDialog) { ui->setupUi(this); setWindowFlags(windowFlags() & (~Qt::WindowContextHelpButtonHint)); @@ -16,9 +14,7 @@ CommentsDialog::CommentsDialog(QWidget *parent) : CommentsDialog::~CommentsDialog() {} -void CommentsDialog::on_buttonBox_accepted() -{ -} +void CommentsDialog::on_buttonBox_accepted() {} void CommentsDialog::on_buttonBox_rejected() { @@ -60,14 +56,14 @@ void CommentsDialog::addOrEditComment(RVA offset, QWidget *parent) } } -bool CommentsDialog::eventFilter(QObject */*obj*/, QEvent *event) +bool CommentsDialog::eventFilter(QObject * /*obj*/, QEvent *event) { - if (event -> type() == QEvent::KeyPress) { - QKeyEvent *keyEvent = static_cast (event); + if (event->type() == QEvent::KeyPress) { + QKeyEvent *keyEvent = static_cast(event); // Confirm comment by pressing Ctrl/Cmd+Return - if ((keyEvent -> modifiers() & Qt::ControlModifier) && - ((keyEvent -> key() == Qt::Key_Enter) || (keyEvent -> key() == Qt::Key_Return))) { + if ((keyEvent->modifiers() & Qt::ControlModifier) + && ((keyEvent->key() == Qt::Key_Enter) || (keyEvent->key() == Qt::Key_Return))) { this->accept(); return true; } diff --git a/src/dialogs/EditFunctionDialog.cpp b/src/dialogs/EditFunctionDialog.cpp index 4a2a6dc4..72deac29 100644 --- a/src/dialogs/EditFunctionDialog.cpp +++ b/src/dialogs/EditFunctionDialog.cpp @@ -1,9 +1,8 @@ #include "EditFunctionDialog.h" #include "ui_EditFunctionDialog.h" -EditFunctionDialog::EditFunctionDialog(QWidget *parent) : - QDialog(parent), - ui(new Ui::EditFunctionDialog) +EditFunctionDialog::EditFunctionDialog(QWidget *parent) + : QDialog(parent), ui(new Ui::EditFunctionDialog) { ui->setupUi(this); setWindowFlags(windowFlags() & (~Qt::WindowContextHelpButtonHint)); @@ -44,21 +43,22 @@ void EditFunctionDialog::setStackSizeText(const QString &stackSize) ui->stackSizeLineEdit->setText(stackSize); } -void EditFunctionDialog::setCallConList(const QStringList &callConList) { +void EditFunctionDialog::setCallConList(const QStringList &callConList) +{ ui->callConComboBox->addItems(callConList); } -void EditFunctionDialog::setCallConSelected(const QString &selected) { +void EditFunctionDialog::setCallConSelected(const QString &selected) +{ ui->callConComboBox->setCurrentText(selected); } -QString EditFunctionDialog::getCallConSelected() { +QString EditFunctionDialog::getCallConSelected() +{ return ui->callConComboBox->currentText(); } -void EditFunctionDialog::on_buttonBox_accepted() -{ -} +void EditFunctionDialog::on_buttonBox_accepted() {} void EditFunctionDialog::on_buttonBox_rejected() { diff --git a/src/dialogs/EditInstructionDialog.cpp b/src/dialogs/EditInstructionDialog.cpp index 6cb7679c..d619bb51 100644 --- a/src/dialogs/EditInstructionDialog.cpp +++ b/src/dialogs/EditInstructionDialog.cpp @@ -2,10 +2,8 @@ #include "ui_EditInstructionDialog.h" #include "core/Cutter.h" -EditInstructionDialog::EditInstructionDialog(InstructionEditMode editMode, QWidget *parent) : - QDialog(parent), - ui(new Ui::EditInstructionDialog), - editMode(editMode) +EditInstructionDialog::EditInstructionDialog(InstructionEditMode editMode, QWidget *parent) + : QDialog(parent), ui(new Ui::EditInstructionDialog), editMode(editMode) { ui->setupUi(this); ui->lineEdit->setMinimumWidth(400); @@ -17,9 +15,7 @@ EditInstructionDialog::EditInstructionDialog(InstructionEditMode editMode, QWidg EditInstructionDialog::~EditInstructionDialog() {} -void EditInstructionDialog::on_buttonBox_accepted() -{ -} +void EditInstructionDialog::on_buttonBox_accepted() {} void EditInstructionDialog::on_buttonBox_rejected() { diff --git a/src/dialogs/EditInstructionDialog.h b/src/dialogs/EditInstructionDialog.h index e80d3e0f..f343ed7d 100644 --- a/src/dialogs/EditInstructionDialog.h +++ b/src/dialogs/EditInstructionDialog.h @@ -8,9 +8,7 @@ namespace Ui { class EditInstructionDialog; } -enum InstructionEditMode { - EDIT_NONE, EDIT_BYTES, EDIT_TEXT -}; +enum InstructionEditMode { EDIT_NONE, EDIT_BYTES, EDIT_TEXT }; class EditInstructionDialog : public QDialog { @@ -32,7 +30,8 @@ private slots: private: std::unique_ptr ui; - InstructionEditMode editMode; // true if editing intruction **bytes**; false if editing instruction **text** + InstructionEditMode + editMode; // true if editing intruction **bytes**; false if editing instruction **text** }; #endif // EDITINSTRUCTIONDIALOG_H diff --git a/src/dialogs/EditMethodDialog.cpp b/src/dialogs/EditMethodDialog.cpp index 041fce8e..eb8d1a0a 100644 --- a/src/dialogs/EditMethodDialog.cpp +++ b/src/dialogs/EditMethodDialog.cpp @@ -3,9 +3,8 @@ #include -EditMethodDialog::EditMethodDialog(bool classFixed, QWidget *parent) : - QDialog(parent), - ui(new Ui::EditMethodDialog) +EditMethodDialog::EditMethodDialog(bool classFixed, QWidget *parent) + : QDialog(parent), ui(new Ui::EditMethodDialog) { ui->setupUi(this); setWindowFlags(windowFlags() & (~Qt::WindowContextHelpButtonHint)); @@ -24,15 +23,14 @@ EditMethodDialog::EditMethodDialog(bool classFixed, QWidget *parent) : updateVirtualUI(); validateInput(); - connect(ui->virtualCheckBox, &QCheckBox::stateChanged, this, &EditMethodDialog::updateVirtualUI); + connect(ui->virtualCheckBox, &QCheckBox::stateChanged, this, + &EditMethodDialog::updateVirtualUI); connect(ui->nameEdit, &QLineEdit::textChanged, this, &EditMethodDialog::validateInput); } EditMethodDialog::~EditMethodDialog() {} -void EditMethodDialog::on_buttonBox_accepted() -{ -} +void EditMethodDialog::on_buttonBox_accepted() {} void EditMethodDialog::on_buttonBox_rejected() { @@ -73,7 +71,7 @@ void EditMethodDialog::setClass(const QString &className) return; } - for (int i=0; icount(); i++) { + for (int i = 0; i < classComboBox->count(); i++) { QString cls = classComboBox->itemData(i).toString(); if (cls == className) { classComboBox->setCurrentIndex(i); @@ -131,7 +129,8 @@ AnalMethodDescription EditMethodDialog::getMethod() const return ret; } -bool EditMethodDialog::showDialog(const QString &title, bool classFixed, QString *className, AnalMethodDescription *desc, QWidget *parent) +bool EditMethodDialog::showDialog(const QString &title, bool classFixed, QString *className, + AnalMethodDescription *desc, QWidget *parent) { EditMethodDialog dialog(classFixed, parent); dialog.setWindowTitle(title); diff --git a/src/dialogs/EditMethodDialog.h b/src/dialogs/EditMethodDialog.h index c5b2404b..a7a59bcc 100644 --- a/src/dialogs/EditMethodDialog.h +++ b/src/dialogs/EditMethodDialog.h @@ -17,7 +17,8 @@ class EditMethodDialog : public QDialog public: /** - * @param classFixed whether the user should be able to change the class. If false, a QComboBox will be shown, otherwise a plain QLabel. + * @param classFixed whether the user should be able to change the class. If false, a QComboBox + * will be shown, otherwise a plain QLabel. */ explicit EditMethodDialog(bool classFixed, QWidget *parent = nullptr); ~EditMethodDialog(); @@ -37,17 +38,20 @@ public: * @param desc initial data for the method information * @return whether the dialog was accepted by the user */ - static bool showDialog(const QString &title, bool classFixed, QString *className, AnalMethodDescription *desc, QWidget *parent = nullptr); + static bool showDialog(const QString &title, bool classFixed, QString *className, + AnalMethodDescription *desc, QWidget *parent = nullptr); /** * @brief Show the dialog to add a new method a given class */ - static void newMethod(QString className = nullptr, const QString &meth = QString(), QWidget *parent = nullptr); + static void newMethod(QString className = nullptr, const QString &meth = QString(), + QWidget *parent = nullptr); /** * @brief Show the dialog to edit a given method of a given class */ - static void editMethod(const QString &className, const QString &meth, QWidget *parent = nullptr); + static void editMethod(const QString &className, const QString &meth, + QWidget *parent = nullptr); private slots: void on_buttonBox_accepted(); @@ -62,7 +66,8 @@ private: QComboBox *classComboBox = nullptr; QLabel *classLabel = nullptr; /** - * This will only be used when the dialog was created with classFixed = true in order to remember the class name. + * This will only be used when the dialog was created with classFixed = true in order to + * remember the class name. */ QString fixedClass; diff --git a/src/dialogs/EditStringDialog.cpp b/src/dialogs/EditStringDialog.cpp index 9f14d636..8b7cd640 100644 --- a/src/dialogs/EditStringDialog.cpp +++ b/src/dialogs/EditStringDialog.cpp @@ -2,25 +2,24 @@ #include "ui_EditStringDialog.h" EditStringDialog::EditStringDialog(QWidget *parent) - : QDialog(parent) - , ui(new Ui::EditStringDialog{}) + : QDialog(parent), ui(new Ui::EditStringDialog {}) { ui->setupUi(this); ui->spinBox_size->setMinimum(0); ui->lineEdit_address->setMinimumWidth(150); ui->spinBox_size->setFocus(); - ui->comboBox_type->addItems({"Auto", "ASCII/Latin1", "UTF-8"}); + ui->comboBox_type->addItems({ "Auto", "ASCII/Latin1", "UTF-8" }); connect(ui->checkBox_autoSize, &QCheckBox::toggled, ui->spinBox_size, &QSpinBox::setDisabled); } -EditStringDialog::~EditStringDialog() { } +EditStringDialog::~EditStringDialog() {} void EditStringDialog::setStringStartAddress(uint64_t address) { ui->lineEdit_address->setText(QString::number(address, 16)); } -bool EditStringDialog::getStringStartAddress(uint64_t& returnValue) const +bool EditStringDialog::getStringStartAddress(uint64_t &returnValue) const { bool status = false; returnValue = ui->lineEdit_address->text().toLongLong(&status, 16); @@ -34,7 +33,7 @@ void EditStringDialog::setStringSizeValue(uint32_t size) int EditStringDialog::getStringSizeValue() const { - if( ui->checkBox_autoSize->isChecked() ) { + if (ui->checkBox_autoSize->isChecked()) { return -1; } @@ -43,20 +42,16 @@ int EditStringDialog::getStringSizeValue() const EditStringDialog::StringType EditStringDialog::getStringType() const { - const int indexVal = ui->comboBox_type->currentIndex(); + const int indexVal = ui->comboBox_type->currentIndex(); - switch(indexVal) - { - case 0: - { + switch (indexVal) { + case 0: { return EditStringDialog::StringType::Auto; } - case 1: - { + case 1: { return EditStringDialog::StringType::ASCII_LATIN1; } - case 2: - { + case 2: { return EditStringDialog::StringType::UTF8; } default: diff --git a/src/dialogs/EditStringDialog.h b/src/dialogs/EditStringDialog.h index 72fabd8d..2b48e830 100644 --- a/src/dialogs/EditStringDialog.h +++ b/src/dialogs/EditStringDialog.h @@ -13,7 +13,7 @@ class EditStringDialog : public QDialog Q_OBJECT public: - enum class StringType {Auto, ASCII_LATIN1, UTF8}; + enum class StringType { Auto, ASCII_LATIN1, UTF8 }; explicit EditStringDialog(QWidget *parent = nullptr); ~EditStringDialog(); @@ -31,7 +31,6 @@ public: */ bool getStringStartAddress(uint64_t &returnValue) const; - /** * @brief Sets the size of string in the dialog * diff --git a/src/dialogs/EditVariablesDialog.cpp b/src/dialogs/EditVariablesDialog.cpp index 08279111..fe50bc38 100644 --- a/src/dialogs/EditVariablesDialog.cpp +++ b/src/dialogs/EditVariablesDialog.cpp @@ -6,16 +6,13 @@ #include #include - -EditVariablesDialog::EditVariablesDialog(RVA offset, QString initialVar, QWidget *parent) : - QDialog(parent), - ui(new Ui::EditVariablesDialog), - functionAddress(RVA_INVALID) +EditVariablesDialog::EditVariablesDialog(RVA offset, QString initialVar, QWidget *parent) + : QDialog(parent), ui(new Ui::EditVariablesDialog), functionAddress(RVA_INVALID) { ui->setupUi(this); connect(ui->buttonBox, &QDialogButtonBox::accepted, this, &EditVariablesDialog::applyFields); - connect(ui->dropdownLocalVars, &QComboBox::currentIndexChanged, - this, &EditVariablesDialog::updateFields); + connect(ui->dropdownLocalVars, &QComboBox::currentIndexChanged, this, + &EditVariablesDialog::updateFields); QString fcnName = Core()->cmdRawAt("afn.", offset).trimmed(); functionAddress = offset; @@ -61,9 +58,10 @@ void EditVariablesDialog::applyFields() Core()->cmdRaw(QString("afvt %1 %2").arg(desc.name).arg(ui->typeComboBox->currentText())); // TODO Remove all those replace once rizin command parser is fixed - QString newName = ui->nameEdit->text().replace(QLatin1Char(' '), QLatin1Char('_')) - .replace(QLatin1Char('\\'), QLatin1Char('_')) - .replace(QLatin1Char('/'), QLatin1Char('_')); + QString newName = ui->nameEdit->text() + .replace(QLatin1Char(' '), QLatin1Char('_')) + .replace(QLatin1Char('\\'), QLatin1Char('_')) + .replace(QLatin1Char('/'), QLatin1Char('_')); if (newName != desc.name) { Core()->renameFunctionVariable(newName, desc.name, functionAddress); } @@ -86,10 +84,9 @@ void EditVariablesDialog::updateFields() ui->typeComboBox->setCurrentText(desc.type); } - void EditVariablesDialog::populateTypesComboBox() { - //gets all loaded types, structures and enums and puts them in a list + // gets all loaded types, structures and enums and puts them in a list QStringList userStructures; QStringList userEnumerations; diff --git a/src/dialogs/EditVariablesDialog.h b/src/dialogs/EditVariablesDialog.h index f0d0c4c1..10eda901 100644 --- a/src/dialogs/EditVariablesDialog.h +++ b/src/dialogs/EditVariablesDialog.h @@ -13,7 +13,8 @@ class EditVariablesDialog : public QDialog Q_OBJECT public: - explicit EditVariablesDialog(RVA offset, QString initialVar = QString(), QWidget *parent = nullptr); + explicit EditVariablesDialog(RVA offset, QString initialVar = QString(), + QWidget *parent = nullptr); ~EditVariablesDialog(); bool empty() const; diff --git a/src/dialogs/FlagDialog.cpp b/src/dialogs/FlagDialog.cpp index 95907a94..72f719c5 100644 --- a/src/dialogs/FlagDialog.cpp +++ b/src/dialogs/FlagDialog.cpp @@ -4,13 +4,8 @@ #include #include "core/Cutter.h" - -FlagDialog::FlagDialog(RVA offset, QWidget *parent) : - QDialog(parent), - ui(new Ui::FlagDialog), - offset(offset), - flagName(""), - flagOffset(RVA_INVALID) +FlagDialog::FlagDialog(RVA offset, QWidget *parent) + : QDialog(parent), ui(new Ui::FlagDialog), offset(offset), flagName(""), flagOffset(RVA_INVALID) { // Setup UI ui->setupUi(this); @@ -32,13 +27,11 @@ FlagDialog::FlagDialog(RVA offset, QWidget *parent) : } // Connect slots - connect(ui->buttonBox, &QDialogButtonBox::accepted, - this, &FlagDialog::buttonBoxAccepted); - connect(ui->buttonBox, &QDialogButtonBox::rejected, - this, &FlagDialog::buttonBoxRejected); + connect(ui->buttonBox, &QDialogButtonBox::accepted, this, &FlagDialog::buttonBoxAccepted); + connect(ui->buttonBox, &QDialogButtonBox::rejected, this, &FlagDialog::buttonBoxRejected); } -FlagDialog::~FlagDialog() { } +FlagDialog::~FlagDialog() {} void FlagDialog::buttonBoxAccepted() { diff --git a/src/dialogs/FlagDialog.h b/src/dialogs/FlagDialog.h index 1d5fe83c..47dcc89a 100644 --- a/src/dialogs/FlagDialog.h +++ b/src/dialogs/FlagDialog.h @@ -5,7 +5,6 @@ #include #include "core/CutterCommon.h" - namespace Ui { class FlagDialog; } diff --git a/src/dialogs/HexdumpRangeDialog.cpp b/src/dialogs/HexdumpRangeDialog.cpp index 4e8f0b8e..b14b4c53 100644 --- a/src/dialogs/HexdumpRangeDialog.cpp +++ b/src/dialogs/HexdumpRangeDialog.cpp @@ -6,26 +6,25 @@ #include #include "core/Cutter.h" -HexdumpRangeDialog::HexdumpRangeDialog(QWidget *parent, bool allowEmpty) : - QDialog(parent), - ui(new Ui::HexdumpRangeDialog), - allowEmpty(allowEmpty) +HexdumpRangeDialog::HexdumpRangeDialog(QWidget *parent, bool allowEmpty) + : QDialog(parent), ui(new Ui::HexdumpRangeDialog), allowEmpty(allowEmpty) { ui->setupUi(this); - QRegularExpressionValidator *v = new QRegularExpressionValidator(QRegularExpression("(?:0[xX])?[0-9a-fA-F]+"), this); + QRegularExpressionValidator *v = + new QRegularExpressionValidator(QRegularExpression("(?:0[xX])?[0-9a-fA-F]+"), this); ui->lengthLineEdit->setValidator(v); ui->startAddressLineEdit->setValidator(v); ui->endAddressLineEdit->setValidator(v); - //subscribe to a text change slot - connect(ui->startAddressLineEdit, &QLineEdit::textEdited, this, &HexdumpRangeDialog::textEdited); + // subscribe to a text change slot + connect(ui->startAddressLineEdit, &QLineEdit::textEdited, this, + &HexdumpRangeDialog::textEdited); connect(ui->endAddressLineEdit, &QLineEdit::textEdited, this, &HexdumpRangeDialog::textEdited); connect(ui->lengthLineEdit, &QLineEdit::textEdited, this, &HexdumpRangeDialog::textEdited); connect(ui->endAddressRadioButton, &QRadioButton::clicked, this, &HexdumpRangeDialog::on_radioButtonClicked); connect(ui->lengthRadioButton, &QRadioButton::clicked, this, &HexdumpRangeDialog::on_radioButtonClicked); - } HexdumpRangeDialog::~HexdumpRangeDialog() @@ -60,8 +59,7 @@ bool HexdumpRangeDialog::getLengthRadioButtonChecked() const void HexdumpRangeDialog::setStartAddress(ut64 start) { - ui->startAddressLineEdit->setText( - QString("0x%1").arg(start, 0, 16)); + ui->startAddressLineEdit->setText(QString("0x%1").arg(start, 0, 16)); } void HexdumpRangeDialog::open(ut64 start) @@ -84,11 +82,10 @@ bool HexdumpRangeDialog::validate() endAddress = Core()->math(ui->endAddressLineEdit->text()); if (endAddress > startAddress) { length = endAddress - startAddress; - ui->lengthLineEdit->setText( - QString("0x%1").arg(length, 0, 16)); + ui->lengthLineEdit->setText(QString("0x%1").arg(length, 0, 16)); this->endAddress = endAddress - 1; emptyRange = false; - } else if (endAddress == startAddress) { + } else if (endAddress == startAddress) { ui->lengthLineEdit->setText("0"); return allowEmpty; } else { @@ -96,7 +93,7 @@ bool HexdumpRangeDialog::validate() return false; } } else { - //we edited the length, so update the end address to be start address + length + // we edited the length, so update the end address to be start address + length length = Core()->math(ui->lengthLineEdit->text()); if (length == 0) { ui->endAddressLineEdit->setText("Empty"); @@ -108,11 +105,9 @@ bool HexdumpRangeDialog::validate() endAddress = startAddress + length - 1; emptyRange = false; if (endAddress == UINT64_MAX) { - ui->endAddressLineEdit->setText( - QString("2^64")); + ui->endAddressLineEdit->setText(QString("2^64")); } else { - ui->endAddressLineEdit->setText( - QString("0x%1").arg(endAddress + 1, 0, 16)); + ui->endAddressLineEdit->setText(QString("0x%1").arg(endAddress + 1, 0, 16)); } } } diff --git a/src/dialogs/HexdumpRangeDialog.h b/src/dialogs/HexdumpRangeDialog.h index 3ba04465..c3f3d288 100644 --- a/src/dialogs/HexdumpRangeDialog.h +++ b/src/dialogs/HexdumpRangeDialog.h @@ -4,7 +4,6 @@ #include "core/CutterCommon.h" #include - namespace Ui { class HexdumpRangeDialog; } @@ -20,8 +19,8 @@ public: ut64 getStartAddress() const; ut64 getEndAddress() const; - void setStartAddress(ut64 start); - void open(ut64 start); + void setStartAddress(ut64 start); + void open(ut64 start); public slots: void textEdited(); @@ -39,7 +38,6 @@ private: private slots: void on_radioButtonClicked(bool checked); - }; #endif // HEXDUMPRANGEDIALOG_H diff --git a/src/dialogs/InitialOptionsDialog.cpp b/src/dialogs/InitialOptionsDialog.cpp index ccf4ab20..56709b69 100644 --- a/src/dialogs/InitialOptionsDialog.cpp +++ b/src/dialogs/InitialOptionsDialog.cpp @@ -15,12 +15,11 @@ #include "core/Cutter.h" #include "common/AnalTask.h" - -InitialOptionsDialog::InitialOptionsDialog(MainWindow *main): - QDialog(nullptr), // parent must not be main - ui(new Ui::InitialOptionsDialog), - main(main), - core(Core()) +InitialOptionsDialog::InitialOptionsDialog(MainWindow *main) + : QDialog(nullptr), // parent must not be main + ui(new Ui::InitialOptionsDialog), + main(main), + core(Core()) { ui->setupUi(this); setWindowFlags(windowFlags() & (~Qt::WindowContextHelpButtonHint)); @@ -32,7 +31,7 @@ InitialOptionsDialog::InitialOptionsDialog(MainWindow *main): ui->archComboBox->addItem(plugin.name, plugin.name); } - setTooltipWithConfigHelp(ui->archComboBox,"asm.arch"); + setTooltipWithConfigHelp(ui->archComboBox, "asm.arch"); // cpu combo box ui->cpuComboBox->lineEdit()->setPlaceholderText(tr("Auto")); @@ -65,19 +64,23 @@ InitialOptionsDialog::InitialOptionsDialog(MainWindow *main): { { "aaft", tr("Type and Argument matching analysis") }, new QCheckBox(), false }, { { "aaT", tr("Analyze code after trap-sleds") }, new QCheckBox(), false }, { { "aap", tr("Analyze function preludes") }, new QCheckBox(), false }, - { { "e! analysis.jmp.tbl", tr("Analyze jump tables in switch statements") }, new QCheckBox(), false }, - { { "e! analysis.pushret", tr("Analyze PUSH+RET as JMP") }, new QCheckBox(), false }, - { { "e! analysis.hasnext", tr("Continue analysis after each function") }, new QCheckBox(), false }}; + { { "e! analysis.jmp.tbl", tr("Analyze jump tables in switch statements") }, + new QCheckBox(), + false }, + { { "e! analysis.pushret", tr("Analyze PUSH+RET as JMP") }, new QCheckBox(), false }, + { { "e! analysis.hasnext", tr("Continue analysis after each function") }, + new QCheckBox(), + false } + }; // Per each checkbox, set a tooltip desccribing it AnalysisCommands item; - foreach (item, analysisCommands){ + foreach (item, analysisCommands) { item.checkbox->setText(item.commandDesc.description); item.checkbox->setToolTip(item.commandDesc.command); item.checkbox->setChecked(item.checked); ui->verticalLayout_7->addWidget(item.checkbox); } - ui->hideFrame->setVisible(false); ui->analoptionsFrame->setVisible(false); @@ -85,11 +88,13 @@ InitialOptionsDialog::InitialOptionsDialog(MainWindow *main): updatePDBLayout(); - connect(ui->pdbCheckBox, &QCheckBox::stateChanged, this, &InitialOptionsDialog::updatePDBLayout); + connect(ui->pdbCheckBox, &QCheckBox::stateChanged, this, + &InitialOptionsDialog::updatePDBLayout); updateScriptLayout(); - connect(ui->scriptCheckBox, &QCheckBox::stateChanged, this, &InitialOptionsDialog::updateScriptLayout); + connect(ui->scriptCheckBox, &QCheckBox::stateChanged, this, + &InitialOptionsDialog::updateScriptLayout); connect(ui->cancelButton, &QPushButton::clicked, this, &InitialOptionsDialog::reject); @@ -106,11 +111,11 @@ void InitialOptionsDialog::updateCPUComboBox() QString arch = getSelectedArch(); QStringList cpus; if (!arch.isEmpty()) { - auto pluginDescr = std::find_if(asmPlugins.begin(), asmPlugins.end(), [&](const RzAsmPluginDescription &plugin) { - return plugin.name == arch; - }); + auto pluginDescr = std::find_if( + asmPlugins.begin(), asmPlugins.end(), + [&](const RzAsmPluginDescription &plugin) { return plugin.name == arch; }); if (pluginDescr != asmPlugins.end()) { -#if QT_VERSION >= QT_VERSION_CHECK(5,14,0) +#if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0) cpus = pluginDescr->cpus.split(",", Qt::SkipEmptyParts); #else cpus = pluginDescr->cpus.split(",", QString::SkipEmptyParts); @@ -124,9 +129,10 @@ void InitialOptionsDialog::updateCPUComboBox() ui->cpuComboBox->lineEdit()->setText(currentText); } -QList InitialOptionsDialog::getAnalysisCommands(const InitialOptions &options) { +QList InitialOptionsDialog::getAnalysisCommands(const InitialOptions &options) +{ QList commands; - for (auto& commandDesc: options.analCmd) { + for (auto &commandDesc : options.analCmd) { commands << commandDesc.command; } return commands; @@ -136,15 +142,15 @@ void InitialOptionsDialog::loadOptions(const InitialOptions &options) { if (options.analCmd.isEmpty()) { analLevel = 0; - } else if (options.analCmd.first().command == "aaa" ) { + } else if (options.analCmd.first().command == "aaa") { analLevel = 1; - } else if (options.analCmd.first().command == "aaaa" ) { + } else if (options.analCmd.first().command == "aaaa") { analLevel = 2; } else { analLevel = 3; AnalysisCommands item; QList commands = getAnalysisCommands(options); - foreach (item, analysisCommands){ + foreach (item, analysisCommands) { qInfo() << item.commandDesc.command; item.checkbox->setChecked(commands.contains(item.commandDesc.command)); } @@ -173,20 +179,16 @@ void InitialOptionsDialog::loadOptions(const InitialOptions &options) ui->entry_loadOffset->setText(RAddressString(options.binLoadAddr)); } - ui->writeCheckBox->setChecked(options.writeEnabled); - + ui->writeCheckBox->setChecked(options.writeEnabled); // TODO: all other options should also be applied to the ui } - -void InitialOptionsDialog::setTooltipWithConfigHelp(QWidget *w, const char *config) { - w->setToolTip(QString("%1 (%2)") - .arg(core->getConfigDescription(config)) - .arg(config)); +void InitialOptionsDialog::setTooltipWithConfigHelp(QWidget *w, const char *config) +{ + w->setToolTip(QString("%1 (%2)").arg(core->getConfigDescription(config)).arg(config)); } - QString InitialOptionsDialog::getSelectedArch() const { QVariant archValue = ui->archComboBox->currentData(); @@ -235,8 +237,8 @@ QList InitialOptionsDialog::getSelectedAdvancedAnalCmds() co QList advanced = QList(); if (ui->analSlider->value() == 3) { AnalysisCommands item; - foreach (item, analysisCommands){ - if(item.checkbox->isChecked()) { + foreach (item, analysisCommands) { + if (item.checkbox->isChecked()) { advanced << item.commandDesc; } } @@ -259,8 +261,8 @@ void InitialOptionsDialog::setupAndStartAnalysis(/*int level, QList adv options.binLoadAddr = Core()->math(ui->entry_loadOffset->text()); } - options.mapAddr = Core()->math( - ui->entry_mapOffset->text()); // Where to map the file once loaded (-m) + options.mapAddr = + Core()->math(ui->entry_mapOffset->text()); // Where to map the file once loaded (-m) options.arch = getSelectedArch(); options.cpu = getSelectedCPU(); options.bits = getSelectedBits(); @@ -280,16 +282,15 @@ void InitialOptionsDialog::setupAndStartAnalysis(/*int level, QList adv options.script = ui->scriptLineEdit->text(); } - options.endian = getSelectedEndianness(); int level = ui->analSlider->value(); switch (level) { case 1: - options.analCmd = { {"aaa", "Auto analysis"} }; + options.analCmd = { { "aaa", "Auto analysis" } }; break; case 2: - options.analCmd = { {"aaaa", "Auto analysis (experimental)"} }; + options.analCmd = { { "aaaa", "Auto analysis (experimental)" } }; break; case 3: options.analCmd = getSelectedAdvancedAnalCmds(); @@ -299,7 +300,6 @@ void InitialOptionsDialog::setupAndStartAnalysis(/*int level, QList adv break; } - AnalTask *analTask = new AnalTask(); analTask->setOptions(options); @@ -337,7 +337,7 @@ void InitialOptionsDialog::closeEvent(QCloseEvent *event) QString InitialOptionsDialog::analysisDescription(int level) { - //TODO: replace this with meaningful descriptions + // TODO: replace this with meaningful descriptions switch (level) { case 0: return tr("No analysis"); @@ -417,7 +417,6 @@ void InitialOptionsDialog::on_pdbSelectButton_clicked() } } - void InitialOptionsDialog::updateScriptLayout() { ui->scriptWidget->setEnabled(ui->scriptCheckBox->isChecked()); @@ -440,7 +439,6 @@ void InitialOptionsDialog::on_scriptSelectButton_clicked() } } - void InitialOptionsDialog::reject() { done(0); diff --git a/src/dialogs/InitialOptionsDialog.h b/src/dialogs/InitialOptionsDialog.h index 73637ee1..f8c24003 100644 --- a/src/dialogs/InitialOptionsDialog.h +++ b/src/dialogs/InitialOptionsDialog.h @@ -48,9 +48,9 @@ private: int analLevel; QList asmPlugins; - void updateCPUComboBox(); - struct AnalysisCommands { + struct AnalysisCommands + { CommandDescription commandDesc; QCheckBox *checkbox; bool checked; diff --git a/src/dialogs/LayoutManager.cpp b/src/dialogs/LayoutManager.cpp index c8e1bb76..d1548964 100644 --- a/src/dialogs/LayoutManager.cpp +++ b/src/dialogs/LayoutManager.cpp @@ -5,21 +5,18 @@ using namespace Cutter; -LayoutManager::LayoutManager(QMap &layouts, QWidget *parent) : - QDialog(parent), - ui(new Ui::LayoutManager), - layouts(layouts) +LayoutManager::LayoutManager(QMap &layouts, QWidget *parent) + : QDialog(parent), ui(new Ui::LayoutManager), layouts(layouts) { ui->setupUi(this); connect(ui->renameButton, &QPushButton::clicked, this, &LayoutManager::renameCurrentLayout); connect(ui->deleteButton, &QPushButton::clicked, this, &LayoutManager::deleteLayout); - connect(ui->layoutSelector, &QComboBox::currentTextChanged, this, &LayoutManager::updateButtons); + connect(ui->layoutSelector, &QComboBox::currentTextChanged, this, + &LayoutManager::updateButtons); refreshNameList(); } -LayoutManager::~LayoutManager() -{ -} +LayoutManager::~LayoutManager() {} void LayoutManager::refreshNameList(QString selection) { @@ -42,10 +39,11 @@ void LayoutManager::renameCurrentLayout() QString newName; while (newName.isEmpty() || isBuiltinLayoutName(newName) || layouts.contains(newName)) { if (!newName.isEmpty()) { - QMessageBox::warning(this, tr("Rename layout error"), tr("'%1' is already used.").arg(newName)); + QMessageBox::warning(this, tr("Rename layout error"), + tr("'%1' is already used.").arg(newName)); } - newName = QInputDialog::getText(this, tr("Save layout"), tr("Enter name"), QLineEdit::Normal, - current); + newName = QInputDialog::getText(this, tr("Save layout"), tr("Enter name"), + QLineEdit::Normal, current); if (newName.isEmpty()) { return; } diff --git a/src/dialogs/LinkTypeDialog.cpp b/src/dialogs/LinkTypeDialog.cpp index bedf377e..837087fc 100644 --- a/src/dialogs/LinkTypeDialog.cpp +++ b/src/dialogs/LinkTypeDialog.cpp @@ -1,9 +1,7 @@ #include "LinkTypeDialog.h" #include "ui_LinkTypeDialog.h" -LinkTypeDialog::LinkTypeDialog(QWidget *parent) : - QDialog(parent), - ui(new Ui::LinkTypeDialog) +LinkTypeDialog::LinkTypeDialog(QWidget *parent) : QDialog(parent), ui(new Ui::LinkTypeDialog) { addrValid = false; @@ -49,7 +47,6 @@ bool LinkTypeDialog::setDefaultAddress(const QString &address) return true; } - void LinkTypeDialog::done(int r) { if (r == QDialog::Accepted) { diff --git a/src/dialogs/MapFileDialog.cpp b/src/dialogs/MapFileDialog.cpp index 72c53ba1..dfcd2647 100644 --- a/src/dialogs/MapFileDialog.cpp +++ b/src/dialogs/MapFileDialog.cpp @@ -5,9 +5,7 @@ #include -MapFileDialog::MapFileDialog(QWidget *parent): - QDialog(parent), - ui(new Ui::MapFileDialog) +MapFileDialog::MapFileDialog(QWidget *parent) : QDialog(parent), ui(new Ui::MapFileDialog) { ui->setupUi(this); } diff --git a/src/dialogs/MultitypeFileSaveDialog.cpp b/src/dialogs/MultitypeFileSaveDialog.cpp index 5ac6aa1e..4e3d7a2c 100644 --- a/src/dialogs/MultitypeFileSaveDialog.cpp +++ b/src/dialogs/MultitypeFileSaveDialog.cpp @@ -4,9 +4,7 @@ #include - -MultitypeFileSaveDialog::MultitypeFileSaveDialog(QWidget *parent, - const QString &caption, +MultitypeFileSaveDialog::MultitypeFileSaveDialog(QWidget *parent, const QString &caption, const QString &directory) : QFileDialog(parent, caption, directory) { @@ -16,14 +14,14 @@ MultitypeFileSaveDialog::MultitypeFileSaveDialog(QWidget *parent, connect(this, &QFileDialog::filterSelected, this, &MultitypeFileSaveDialog::onFilterSelected); } -void MultitypeFileSaveDialog::setTypes(const QVector - types, bool useDetection) +void MultitypeFileSaveDialog::setTypes( + const QVector types, bool useDetection) { this->hasTypeDetection = useDetection; this->types.clear(); this->types.reserve(types.size() + (useDetection ? 1 : 0)); if (useDetection) { - this->types.push_back(TypeDescription{tr("Detect type (*)"), "", QVariant()}); + this->types.push_back(TypeDescription { tr("Detect type (*)"), "", QVariant() }); } this->types.append(types); QStringList filters; @@ -43,9 +41,10 @@ MultitypeFileSaveDialog::TypeDescription MultitypeFileSaveDialog::selectedType() if (hasTypeDetection && filterIt == this->types.begin()) { QFileInfo info(this->selectedFiles().first()); QString currentSuffix = info.suffix(); - filterIt = std::find_if(types.begin(), types.end(), [¤tSuffix](const TypeDescription & v) { - return currentSuffix == v.extension; - }); + filterIt = std::find_if(types.begin(), types.end(), + [¤tSuffix](const TypeDescription &v) { + return currentSuffix == v.extension; + }); if (filterIt != types.end()) { return *filterIt; } @@ -96,8 +95,7 @@ void MultitypeFileSaveDialog::onFilterSelected(const QString &filter) QVector::const_iterator MultitypeFileSaveDialog::findType(const QString &description) const { - return std::find_if(types.begin(), types.end(), - [&description](const TypeDescription & v) { + return std::find_if(types.begin(), types.end(), [&description](const TypeDescription &v) { return v.description == description; }); } diff --git a/src/dialogs/MultitypeFileSaveDialog.h b/src/dialogs/MultitypeFileSaveDialog.h index f92fe3fb..51ccb7f7 100644 --- a/src/dialogs/MultitypeFileSaveDialog.h +++ b/src/dialogs/MultitypeFileSaveDialog.h @@ -10,20 +10,22 @@ class MultitypeFileSaveDialog : public QFileDialog Q_OBJECT public: - struct TypeDescription { + struct TypeDescription + { QString description; QString extension; QVariant data; }; - explicit MultitypeFileSaveDialog(QWidget *parent = nullptr, - const QString &caption = QString(), + explicit MultitypeFileSaveDialog(QWidget *parent = nullptr, const QString &caption = QString(), const QString &directory = QString()); void setTypes(const QVector types, bool useDetection = true); TypeDescription selectedType() const; + protected: void done(int r) override; + private: void onFilterSelected(const QString &filter); QVector::const_iterator findType(const QString &description) const; diff --git a/src/dialogs/NativeDebugDialog.cpp b/src/dialogs/NativeDebugDialog.cpp index f8b0f453..3d81f04c 100644 --- a/src/dialogs/NativeDebugDialog.cpp +++ b/src/dialogs/NativeDebugDialog.cpp @@ -3,9 +3,8 @@ #include -NativeDebugDialog::NativeDebugDialog(QWidget *parent) : - QDialog(parent), - ui(new Ui::NativeDebugDialog) +NativeDebugDialog::NativeDebugDialog(QWidget *parent) + : QDialog(parent), ui(new Ui::NativeDebugDialog) { ui->setupUi(this); setWindowFlags(windowFlags() & (~Qt::WindowContextHelpButtonHint)); diff --git a/src/dialogs/NewFileDialog.cpp b/src/dialogs/NewFileDialog.cpp index 4d472545..a45aa75c 100644 --- a/src/dialogs/NewFileDialog.cpp +++ b/src/dialogs/NewFileDialog.cpp @@ -21,9 +21,9 @@ static QColor getColorFor(int pos) QColor(29, 188, 156), // Turquoise QColor(52, 152, 219), // Blue QColor(155, 89, 182), // Violet - QColor(52, 73, 94), // Grey - QColor(231, 76, 60), // Red - QColor(243, 156, 17) // Orange + QColor(52, 73, 94), // Grey + QColor(231, 76, 60), // Red + QColor(243, 156, 17) // Orange }; return colors[pos % colors.size()]; } @@ -51,10 +51,10 @@ static QIcon getIconFor(const QString &str, int pos) return QIcon(pixmap); } -NewFileDialog::NewFileDialog(MainWindow *main) : - QDialog(nullptr), // no parent on purpose, using main causes weird positioning - ui(new Ui::NewFileDialog), - main(main) +NewFileDialog::NewFileDialog(MainWindow *main) + : QDialog(nullptr), // no parent on purpose, using main causes weird positioning + ui(new Ui::NewFileDialog), + main(main) { ui->setupUi(this); setWindowFlags(windowFlags() & (~Qt::WindowContextHelpButtonHint)); @@ -88,8 +88,8 @@ void NewFileDialog::on_loadFileButton_clicked() void NewFileDialog::on_selectFileButton_clicked() { QString currentDir = Config()->getRecentFolder(); - const QString &fileName = QDir::toNativeSeparators(QFileDialog::getOpenFileName(this, - tr("Select file"), currentDir)); + const QString &fileName = QDir::toNativeSeparators( + QFileDialog::getOpenFileName(this, tr("Select file"), currentDir)); if (!fileName.isEmpty()) { ui->newFileEdit->setText(fileName); @@ -100,8 +100,8 @@ void NewFileDialog::on_selectFileButton_clicked() void NewFileDialog::on_selectProjectFileButton_clicked() { - const QString &fileName = QDir::toNativeSeparators( - QFileDialog::getOpenFileName(this, tr("Open Project"))); + const QString &fileName = + QDir::toNativeSeparators(QFileDialog::getOpenFileName(this, tr("Open Project"))); if (!fileName.isEmpty()) { ui->projectFileEdit->setText(fileName); @@ -252,12 +252,10 @@ static QStringList fillFilesList(QListWidget *widget, const QStringList &files) it.remove(); } else { // Format the text and add the item to the file list - const QString text = QString("%1\n%2\nSize: %3").arg(basename, filenameHome, - qhelpers::formatBytecount(info.size())); - QListWidgetItem *item = new QListWidgetItem( - getIconFor(basename, i++), - text - ); + const QString text = + QString("%1\n%2\nSize: %3") + .arg(basename, filenameHome, qhelpers::formatBytecount(info.size())); + QListWidgetItem *item = new QListWidgetItem(getIconFor(basename, i++), text); item->setData(Qt::UserRole, fullpath); widget->addItem(item); } @@ -316,7 +314,7 @@ void NewFileDialog::loadFile(const QString &filename) { const QString &nativeFn = QDir::toNativeSeparators(filename); if (ui->ioPlugin->currentIndex() == 0 && !Core()->tryFile(nativeFn, false) - && !ui->checkBox_FilelessOpen->isChecked()) { + && !ui->checkBox_FilelessOpen->isChecked()) { QMessageBox msgBox(this); msgBox.setText(tr("Select a new program or a previous one before continuing.")); msgBox.exec(); diff --git a/src/dialogs/RemoteDebugDialog.cpp b/src/dialogs/RemoteDebugDialog.cpp index a2a9bef5..7a70d11d 100644 --- a/src/dialogs/RemoteDebugDialog.cpp +++ b/src/dialogs/RemoteDebugDialog.cpp @@ -6,32 +6,27 @@ #include #include -enum DbgBackendType { - GDB = 0, - WINDBG = 1 -}; +enum DbgBackendType { GDB = 0, WINDBG = 1 }; -struct DbgBackend { +struct DbgBackend +{ DbgBackendType type; QString name; QString prefix; }; -static const QList dbgBackends = { - { GDB, "GDB", "gdb://" }, - { WINDBG, "WinKd - Pipe", "winkd://" } -}; +static const QList dbgBackends = { { GDB, "GDB", "gdb://" }, + { WINDBG, "WinKd - Pipe", "winkd://" } }; -RemoteDebugDialog::RemoteDebugDialog(QWidget *parent) : - QDialog(parent), - ui(new Ui::RemoteDebugDialog) +RemoteDebugDialog::RemoteDebugDialog(QWidget *parent) + : QDialog(parent), ui(new Ui::RemoteDebugDialog) { ui->setupUi(this); setWindowFlags(windowFlags() & (~Qt::WindowContextHelpButtonHint)); // Fill in debugger Combo ui->debuggerCombo->clear(); - for (auto& backend : dbgBackends) { + for (auto &backend : dbgBackends) { ui->debuggerCombo->addItem(backend.name); } @@ -44,7 +39,8 @@ RemoteDebugDialog::RemoteDebugDialog(QWidget *parent) : ui->recentsIpListWidget->addAction(ui->actionRemoveAll); connect(ui->actionRemoveAll, &QAction::triggered, this, &RemoteDebugDialog::clearAll); connect(ui->actionRemoveItem, &QAction::triggered, this, &RemoteDebugDialog::removeItem); - connect(ui->recentsIpListWidget, &QListWidget::itemClicked, this, &RemoteDebugDialog::itemClicked); + connect(ui->recentsIpListWidget, &QListWidget::itemClicked, this, + &RemoteDebugDialog::itemClicked); } RemoteDebugDialog::~RemoteDebugDialog() {} @@ -102,9 +98,7 @@ bool RemoteDebugDialog::validatePort() return true; } -void RemoteDebugDialog::on_buttonBox_accepted() -{ -} +void RemoteDebugDialog::on_buttonBox_accepted() {} void RemoteDebugDialog::on_buttonBox_rejected() { @@ -148,8 +142,8 @@ void RemoteDebugDialog::fillFormData(QString formdata) { QString ipText = ""; QString portText = ""; - const DbgBackend* backend = nullptr; - for (auto& back : dbgBackends) { + const DbgBackend *backend = nullptr; + for (auto &back : dbgBackends) { if (formdata.startsWith(back.prefix)) { backend = &back; } @@ -172,14 +166,14 @@ void RemoteDebugDialog::fillFormData(QString formdata) ui->portEdit->setText(portText); } - QString RemoteDebugDialog::getUri() const { int debugger = getDebugger(); if (debugger == WINDBG) { return QString("%1%2").arg(dbgBackends[WINDBG].prefix, getIpOrPath()); } else if (debugger == GDB) { - return QString("%1%2:%3").arg(dbgBackends[GDB].prefix, getIpOrPath(), QString::number(getPort())); + return QString("%1%2:%3").arg(dbgBackends[GDB].prefix, getIpOrPath(), + QString::number(getPort())); } return "- uri error"; } @@ -194,9 +188,7 @@ bool RemoteDebugDialog::fillRecentIpList() while (it.hasNext()) { const QString ip = it.next(); const QString text = QString("%1").arg(ip); - QListWidgetItem *item = new QListWidgetItem( - text - ); + QListWidgetItem *item = new QListWidgetItem(text); item->setData(Qt::UserRole, ip); // Fill recentsIpListWidget ui->recentsIpListWidget->addItem(item); diff --git a/src/dialogs/RizinPluginsDialog.cpp b/src/dialogs/RizinPluginsDialog.cpp index f923fa46..8ff12331 100644 --- a/src/dialogs/RizinPluginsDialog.cpp +++ b/src/dialogs/RizinPluginsDialog.cpp @@ -5,9 +5,8 @@ #include "common/Helpers.h" #include "plugins/PluginManager.h" -RizinPluginsDialog::RizinPluginsDialog(QWidget *parent) : - QDialog(parent), - ui(new Ui::RizinPluginsDialog) +RizinPluginsDialog::RizinPluginsDialog(QWidget *parent) + : QDialog(parent), ui(new Ui::RizinPluginsDialog) { ui->setupUi(this); diff --git a/src/dialogs/RizinTaskDialog.cpp b/src/dialogs/RizinTaskDialog.cpp index 65ca6a5b..09a78ac3 100644 --- a/src/dialogs/RizinTaskDialog.cpp +++ b/src/dialogs/RizinTaskDialog.cpp @@ -6,15 +6,11 @@ #include "ui_RizinTaskDialog.h" RizinTaskDialog::RizinTaskDialog(RizinTask::Ptr task, QWidget *parent) - : QDialog(parent), - ui(new Ui::RizinTaskDialog), - task(task) + : QDialog(parent), ui(new Ui::RizinTaskDialog), task(task) { ui->setupUi(this); - connect(task.data(), &RizinTask::finished, this, [this]() { - close(); - }); + connect(task.data(), &RizinTask::finished, this, [this]() { close(); }); connect(&timer, &QTimer::timeout, this, &RizinTaskDialog::updateProgressTimer); timer.setInterval(1000); @@ -25,9 +21,7 @@ RizinTaskDialog::RizinTaskDialog(RizinTask::Ptr task, QWidget *parent) updateProgressTimer(); } -RizinTaskDialog::~RizinTaskDialog() -{ -} +RizinTaskDialog::~RizinTaskDialog() {} void RizinTaskDialog::updateProgressTimer() { @@ -68,5 +62,4 @@ void RizinTaskDialog::reject() { task->breakTask(); setDesc("Attempting to stop the task..."); - } diff --git a/src/dialogs/RizinTaskDialog.h b/src/dialogs/RizinTaskDialog.h index f9ce962b..0b3a3eb0 100644 --- a/src/dialogs/RizinTaskDialog.h +++ b/src/dialogs/RizinTaskDialog.h @@ -24,8 +24,8 @@ public: RizinTaskDialog(Ptr task, QWidget *parent = nullptr); ~RizinTaskDialog(); - void setBreakOnClose(bool v) { breakOnClose = v; } - bool getBreakOnClose() { return breakOnClose; } + void setBreakOnClose(bool v) { breakOnClose = v; } + bool getBreakOnClose() { return breakOnClose; } void setDesc(const QString &label); public slots: @@ -47,4 +47,4 @@ private: bool breakOnClose = false; }; -#endif //RZTASKDIALOG_H +#endif // RZTASKDIALOG_H diff --git a/src/dialogs/SetToDataDialog.cpp b/src/dialogs/SetToDataDialog.cpp index fd283734..92ed96e8 100644 --- a/src/dialogs/SetToDataDialog.cpp +++ b/src/dialogs/SetToDataDialog.cpp @@ -2,10 +2,8 @@ #include "ui_SetToDataDialog.h" #include -SetToDataDialog::SetToDataDialog(RVA startAddr, QWidget *parent) : - QDialog(parent), - ui(new Ui::SetToDataDialog), - startAddress(startAddr) +SetToDataDialog::SetToDataDialog(RVA startAddr, QWidget *parent) + : QDialog(parent), ui(new Ui::SetToDataDialog), startAddress(startAddr) { ui->setupUi(this); auto validator = new QIntValidator(this); diff --git a/src/dialogs/TypesInteractionDialog.cpp b/src/dialogs/TypesInteractionDialog.cpp index 5ff70837..7f7b6a72 100644 --- a/src/dialogs/TypesInteractionDialog.cpp +++ b/src/dialogs/TypesInteractionDialog.cpp @@ -9,9 +9,8 @@ #include #include -TypesInteractionDialog::TypesInteractionDialog(QWidget *parent, bool readOnly) : - QDialog(parent), - ui(new Ui::TypesInteractionDialog) +TypesInteractionDialog::TypesInteractionDialog(QWidget *parent, bool readOnly) + : QDialog(parent), ui(new Ui::TypesInteractionDialog) { ui->setupUi(this); QFont font = Config()->getBaseFont(); @@ -29,7 +28,9 @@ TypesInteractionDialog::~TypesInteractionDialog() {} void TypesInteractionDialog::on_selectFileButton_clicked() { - QString filename = QFileDialog::getOpenFileName(this, tr("Select file"), Config()->getRecentFolder(), "Header files (*.h *.hpp);;All files (*)"); + QString filename = + QFileDialog::getOpenFileName(this, tr("Select file"), Config()->getRecentFolder(), + "Header files (*.h *.hpp);;All files (*)"); if (filename.isEmpty()) { return; } @@ -74,7 +75,8 @@ void TypesInteractionDialog::done(int r) } } -void TypesInteractionDialog::fillTextArea(QString content) { +void TypesInteractionDialog::fillTextArea(QString content) +{ ui->layoutWidget->hide(); ui->plainTextEdit->setPlainText(content); } diff --git a/src/dialogs/VersionInfoDialog.cpp b/src/dialogs/VersionInfoDialog.cpp index c62052ec..79bda724 100644 --- a/src/dialogs/VersionInfoDialog.cpp +++ b/src/dialogs/VersionInfoDialog.cpp @@ -9,10 +9,8 @@ #include #include -VersionInfoDialog::VersionInfoDialog(QWidget *parent) : - QDialog(parent), - ui(new Ui::VersionInfoDialog), - core(Core()) +VersionInfoDialog::VersionInfoDialog(QWidget *parent) + : QDialog(parent), ui(new Ui::VersionInfoDialog), core(Core()) { ui->setupUi(this); setWindowFlags(windowFlags() & (~Qt::WindowContextHelpButtonHint)); @@ -37,7 +35,7 @@ void VersionInfoDialog::fillVersionInfo() ui->leftLabel->setText("Version symbols"); ui->rightLabel->setText("Version need"); - //Left tree + // Left tree QTreeWidgetItem *secNameItemL = new QTreeWidgetItem(); secNameItemL->setText(0, "Section name:"); secNameItemL->setText(1, versym["section_name"].toString()); @@ -110,7 +108,8 @@ void VersionInfoDialog::fillVersionInfo() QTreeWidgetItem *parentItem = new QTreeWidgetItem(); QString parentString; parentItem->setText(0, RAddressString(parentObj["idx"].toDouble())); - parentString.append("Version: " + QString::number(parentObj["vn_version"].toDouble()) + "\t"); + parentString.append("Version: " + QString::number(parentObj["vn_version"].toDouble()) + + "\t"); parentString.append("File: " + parentObj["file_name"].toString()); parentItem->setText(1, parentString); diff --git a/src/dialogs/VersionInfoDialog.h b/src/dialogs/VersionInfoDialog.h index cdc98ed7..7974e059 100644 --- a/src/dialogs/VersionInfoDialog.h +++ b/src/dialogs/VersionInfoDialog.h @@ -23,7 +23,6 @@ private: CutterCore *core; void fillVersionInfo(); - }; #endif // VERSIONINFODIALOG_H diff --git a/src/dialogs/WelcomeDialog.cpp b/src/dialogs/WelcomeDialog.cpp index ed92cac2..c650c308 100644 --- a/src/dialogs/WelcomeDialog.cpp +++ b/src/dialogs/WelcomeDialog.cpp @@ -11,14 +11,13 @@ * @brief Constructs a WelcomeDialog object * @param parent */ -WelcomeDialog::WelcomeDialog(QWidget *parent) : - QDialog(parent), - ui(new Ui::WelcomeDialog) +WelcomeDialog::WelcomeDialog(QWidget *parent) : QDialog(parent), ui(new Ui::WelcomeDialog) { ui->setupUi(this); setWindowFlags(windowFlags() & (~Qt::WindowContextHelpButtonHint)); ui->logoSvgWidget->load(Config()->getLogoFile()); - ui->versionLabel->setText("" + tr("Version ") + CUTTER_VERSION_FULL + ""); + ui->versionLabel->setText("" + tr("Version ") + CUTTER_VERSION_FULL + + ""); ui->themeComboBox->setCurrentIndex(Config()->getInterfaceTheme()); QSignalBlocker s(ui->updatesCheckBox); @@ -33,8 +32,7 @@ WelcomeDialog::WelcomeDialog(QWidget *parent) : } ui->languageComboBox->setCurrentText(curr); connect(ui->languageComboBox, - static_cast(&QComboBox::currentIndexChanged), - this, + static_cast(&QComboBox::currentIndexChanged), this, &WelcomeDialog::onLanguageComboBox_currentIndexChanged); Config()->adjustColorThemeDarkness(); diff --git a/src/dialogs/WriteCommandsDialogs.cpp b/src/dialogs/WriteCommandsDialogs.cpp index 5c388ff2..5826a9ae 100644 --- a/src/dialogs/WriteCommandsDialogs.cpp +++ b/src/dialogs/WriteCommandsDialogs.cpp @@ -7,8 +7,8 @@ #include #include -Base64EnDecodedWriteDialog::Base64EnDecodedWriteDialog(QWidget* parent) : QDialog(parent), - ui(new Ui::Base64EnDecodedWriteDialog) +Base64EnDecodedWriteDialog::Base64EnDecodedWriteDialog(QWidget *parent) + : QDialog(parent), ui(new Ui::Base64EnDecodedWriteDialog) { ui->setupUi(this); ui->decodeRB->click(); @@ -24,19 +24,16 @@ QByteArray Base64EnDecodedWriteDialog::getData() const return ui->base64LineEdit->text().toUtf8(); } -IncrementDecrementDialog::IncrementDecrementDialog(QWidget* parent) : QDialog(parent), - ui(new Ui::IncrementDecrementDialog) +IncrementDecrementDialog::IncrementDecrementDialog(QWidget *parent) + : QDialog(parent), ui(new Ui::IncrementDecrementDialog) { ui->setupUi(this); ui->incrementRB->click(); - ui->nBytesCB->addItems(QStringList() - << tr("Byte") - << tr("Word") - << tr("Dword") - << tr("Qword")); + ui->nBytesCB->addItems(QStringList() << tr("Byte") << tr("Word") << tr("Dword") << tr("Qword")); - ui->valueLE->setValidator(new QRegularExpressionValidator(QRegularExpression("[0-9a-fA-Fx]{1,18}"), ui->valueLE)); + ui->valueLE->setValidator( + new QRegularExpressionValidator(QRegularExpression("[0-9a-fA-Fx]{1,18}"), ui->valueLE)); } IncrementDecrementDialog::Mode IncrementDecrementDialog::getMode() const @@ -56,14 +53,16 @@ uint64_t IncrementDecrementDialog::getValue() const return Core()->math(ui->valueLE->text()); } -DuplicateFromOffsetDialog::DuplicateFromOffsetDialog(QWidget* parent) : QDialog(parent), - ui(new Ui::DuplicateFromOffsetDialog) +DuplicateFromOffsetDialog::DuplicateFromOffsetDialog(QWidget *parent) + : QDialog(parent), ui(new Ui::DuplicateFromOffsetDialog) { ui->setupUi(this); ui->bytesLabel->setFont(QFontDatabase::systemFont(QFontDatabase::FixedFont)); - ui->offsetLE->setValidator(new QRegularExpressionValidator(QRegularExpression("[0-9a-fA-Fx]{1,18}"), ui->offsetLE)); + ui->offsetLE->setValidator(new QRegularExpressionValidator( + QRegularExpression("[0-9a-fA-Fx]{1,18}"), ui->offsetLE)); connect(ui->offsetLE, &QLineEdit::textChanged, this, &DuplicateFromOffsetDialog::refresh); - connect(ui->nBytesSB, static_cast(&QSpinBox::valueChanged), this, &DuplicateFromOffsetDialog::refresh); + connect(ui->nBytesSB, static_cast(&QSpinBox::valueChanged), this, + &DuplicateFromOffsetDialog::refresh); } RVA DuplicateFromOffsetDialog::getOffset() const @@ -83,11 +82,9 @@ void DuplicateFromOffsetDialog::refresh() QSignalBlocker sb(Core()); // Add space every two characters for word wrap in hex sequence - QRegularExpression re{"(.{2})"}; - QString bytes = Core()->cmdRawAt(QString("p8 %1") - .arg(QString::number(getNBytes())), - offestFrom) - .replace(re, "\\1 "); + QRegularExpression re { "(.{2})" }; + QString bytes = Core()->cmdRawAt(QString("p8 %1").arg(QString::number(getNBytes())), offestFrom) + .replace(re, "\\1 "); ui->bytesLabel->setText(bytes.trimmed()); } diff --git a/src/dialogs/WriteCommandsDialogs.h b/src/dialogs/WriteCommandsDialogs.h index 3d8428fc..2f4a2052 100644 --- a/src/dialogs/WriteCommandsDialogs.h +++ b/src/dialogs/WriteCommandsDialogs.h @@ -20,7 +20,7 @@ public: QByteArray getData() const; private: - Ui::Base64EnDecodedWriteDialog* ui; + Ui::Base64EnDecodedWriteDialog *ui; }; class IncrementDecrementDialog : public QDialog @@ -34,7 +34,7 @@ public: uint64_t getValue() const; private: - Ui::IncrementDecrementDialog* ui; + Ui::IncrementDecrementDialog *ui; }; class DuplicateFromOffsetDialog : public QDialog @@ -46,7 +46,7 @@ public: size_t getNBytes() const; private: - Ui::DuplicateFromOffsetDialog* ui; + Ui::DuplicateFromOffsetDialog *ui; private slots: void refresh(); diff --git a/src/dialogs/XrefsDialog.cpp b/src/dialogs/XrefsDialog.cpp index dfe582c6..8a9fe3f5 100644 --- a/src/dialogs/XrefsDialog.cpp +++ b/src/dialogs/XrefsDialog.cpp @@ -8,12 +8,8 @@ #include -XrefsDialog::XrefsDialog(MainWindow *parent, bool hideXrefFrom) : - QDialog(parent), - addr(0), - toModel(this), - fromModel(this), - ui(new Ui::XrefsDialog) +XrefsDialog::XrefsDialog(MainWindow *parent, bool hideXrefFrom) + : QDialog(parent), addr(0), toModel(this), fromModel(this), ui(new Ui::XrefsDialog) { ui->setupUi(this); setWindowFlags(windowFlags() & (~Qt::WindowContextHelpButtonHint)); @@ -24,7 +20,8 @@ XrefsDialog::XrefsDialog(MainWindow *parent, bool hideXrefFrom) : ui->toTreeWidget->setModel(&toModel); ui->fromTreeWidget->setModel(&fromModel); - // Modify the splitter's location to show more Disassembly instead of empty space. Not possible via Designer + // Modify the splitter's location to show more Disassembly instead of empty space. Not possible + // via Designer ui->splitter->setSizes(QList() << 300 << 400); // Increase asm text edit margin @@ -35,14 +32,15 @@ XrefsDialog::XrefsDialog(MainWindow *parent, bool hideXrefFrom) : setupPreviewFont(); // Highlight current line - connect(ui->previewTextEdit, &QPlainTextEdit::cursorPositionChanged, this, &XrefsDialog::highlightCurrentLine); + connect(ui->previewTextEdit, &QPlainTextEdit::cursorPositionChanged, this, + &XrefsDialog::highlightCurrentLine); connect(Config(), &Configuration::fontsUpdated, this, &XrefsDialog::setupPreviewFont); connect(Config(), &Configuration::colorsUpdated, this, &XrefsDialog::setupPreviewColors); - connect(ui->toTreeWidget->selectionModel(), &QItemSelectionModel::selectionChanged, - this, &XrefsDialog::onToTreeWidgetItemSelectionChanged); - connect(ui->fromTreeWidget->selectionModel(), &QItemSelectionModel::selectionChanged, - this, &XrefsDialog::onFromTreeWidgetItemSelectionChanged); + connect(ui->toTreeWidget->selectionModel(), &QItemSelectionModel::selectionChanged, this, + &XrefsDialog::onToTreeWidgetItemSelectionChanged); + connect(ui->fromTreeWidget->selectionModel(), &QItemSelectionModel::selectionChanged, this, + &XrefsDialog::onFromTreeWidgetItemSelectionChanged); // Don't create recursive xref dialogs auto toContextMenu = ui->toTreeWidget->getItemContextMenu(); @@ -63,7 +61,7 @@ XrefsDialog::XrefsDialog(MainWindow *parent, bool hideXrefFrom) : } } -XrefsDialog::~XrefsDialog() { } +XrefsDialog::~XrefsDialog() {} QString XrefsDialog::normalizeAddr(const QString &addr) const { @@ -82,9 +80,10 @@ void XrefsDialog::setupPreviewFont() void XrefsDialog::setupPreviewColors() { - ui->previewTextEdit->setStyleSheet(QString("QPlainTextEdit { background-color: %1; color: %2; }") - .arg(ConfigColor("gui.background").name()) - .arg(ConfigColor("btext").name())); + ui->previewTextEdit->setStyleSheet( + QString("QPlainTextEdit { background-color: %1; color: %2; }") + .arg(ConfigColor("gui.background").name()) + .arg(ConfigColor("btext").name())); } void XrefsDialog::highlightCurrentLine() @@ -144,7 +143,8 @@ void XrefsDialog::updatePreview(RVA addr) void XrefsDialog::updateLabels(QString name) { ui->label_xTo->setText(tr("X-Refs to %1 (%2 results):").arg(name).arg(toModel.rowCount())); - ui->label_xFrom->setText(tr("X-Refs from %1 (%2 results):").arg(name).arg(fromModel.rowCount())); + ui->label_xFrom->setText( + tr("X-Refs from %1 (%2 results):").arg(name).arg(fromModel.rowCount())); } void XrefsDialog::updateLabelsForVariables(QString name) @@ -213,11 +213,7 @@ QString XrefModel::xrefTypeString(const QString &type) return type; } - -XrefModel::XrefModel(QObject *parent) - : AddressableItemModel(parent) -{ -} +XrefModel::XrefModel(QObject *parent) : AddressableItemModel(parent) {} void XrefModel::readForOffset(RVA offset, bool to, bool whole_function) { diff --git a/src/dialogs/XrefsDialog.h b/src/dialogs/XrefsDialog.h index b3fd7a28..09cfcb6e 100644 --- a/src/dialogs/XrefsDialog.h +++ b/src/dialogs/XrefsDialog.h @@ -8,11 +8,12 @@ #include "core/Cutter.h" #include "common/AddressableItemModel.h" -class XrefModel: public AddressableItemModel +class XrefModel : public AddressableItemModel { private: QList xrefs; bool to; + public: enum Columns { OFFSET = 0, TYPE, CODE, COMMENT, COUNT }; static const int FlagDescriptionRole = Qt::UserRole; @@ -32,7 +33,6 @@ public: static QString xrefTypeString(const QString &type); }; - class MainWindow; namespace Ui { @@ -44,14 +44,15 @@ class XrefsDialog : public QDialog Q_OBJECT public: - explicit XrefsDialog(MainWindow *parent, bool hideXrefFrom=false); + explicit XrefsDialog(MainWindow *parent, bool hideXrefFrom = false); ~XrefsDialog(); void fillRefsForAddress(RVA addr, QString name, bool whole_function); /** - * @brief Initializes toModel and fromModel with the details about the references to the specified - * local variable 'nameOfVariable'. - * @param nameOfVarible Name of the local variable for which the references are being initialized. + * @brief Initializes toModel and fromModel with the details about the references to the + * specified local variable 'nameOfVariable'. + * @param nameOfVarible Name of the local variable for which the references are being + * initialized. * @param offset An offset in the function in which the specified local variable exist. */ void fillRefsForVariable(QString nameOfVariable, RVA offset); diff --git a/src/dialogs/preferences/AnalOptionsWidget.cpp b/src/dialogs/preferences/AnalOptionsWidget.cpp index f3d87355..83ed18b6 100644 --- a/src/dialogs/preferences/AnalOptionsWidget.cpp +++ b/src/dialogs/preferences/AnalOptionsWidget.cpp @@ -9,29 +9,26 @@ #include "core/MainWindow.h" static const QHash analBoundaries { - {"io.maps.x", "All executable maps"}, - {"io.maps", "All maps"}, - {"io.map", "Current map"}, - {"raw", "Raw"}, - {"bin.section", "Current mapped section"}, - {"bin.sections", "All mapped sections"}, + { "io.maps.x", "All executable maps" }, + { "io.maps", "All maps" }, + { "io.map", "Current map" }, + { "raw", "Raw" }, + { "bin.section", "Current mapped section" }, + { "bin.sections", "All mapped sections" }, }; AnalOptionsWidget::AnalOptionsWidget(PreferencesDialog *dialog) - : QDialog(dialog), - ui(new Ui::AnalOptionsWidget) + : QDialog(dialog), ui(new Ui::AnalOptionsWidget) { ui->setupUi(this); - checkboxes = { - { ui->autonameCheckbox, "analysis.autoname" }, - { ui->hasnextCheckbox, "analysis.hasnext" }, - { ui->jmpRefCheckbox, "analysis.jmp.ref" }, - { ui->jmpTblCheckbox, "analysis.jmp.tbl" }, - { ui->pushRetCheckBox, "analysis.pushret" }, - { ui->typesVerboseCheckBox, "analysis.types.verbose" }, - { ui->verboseCheckBox, "analysis.verbose" } - }; + checkboxes = { { ui->autonameCheckbox, "analysis.autoname" }, + { ui->hasnextCheckbox, "analysis.hasnext" }, + { ui->jmpRefCheckbox, "analysis.jmp.ref" }, + { ui->jmpTblCheckbox, "analysis.jmp.tbl" }, + { ui->pushRetCheckBox, "analysis.pushret" }, + { ui->typesVerboseCheckBox, "analysis.types.verbose" }, + { ui->verboseCheckBox, "analysis.verbose" } }; // Create list of options for the analysis.in selector createAnalInOptionsList(); @@ -40,7 +37,8 @@ AnalOptionsWidget::AnalOptionsWidget(PreferencesDialog *dialog) for (ConfigCheckbox &confCheckbox : checkboxes) { QString val = confCheckbox.config; QCheckBox &cb = *confCheckbox.checkBox; - connect(confCheckbox.checkBox, &QCheckBox::stateChanged, this, [this, val, &cb]() { checkboxEnabler(&cb, val); }); + connect(confCheckbox.checkBox, &QCheckBox::stateChanged, this, + [this, val, &cb]() { checkboxEnabler(&cb, val); }); } ui->analyzePushButton->setToolTip("Analyze the program using Rizin's \"aaa\" command"); @@ -51,7 +49,8 @@ AnalOptionsWidget::AnalOptionsWidget(PreferencesDialog *dialog) &AnalOptionsWidget::updateAnalIn); connect(ui->ptrDepthSpinBox, &QSpinBox::valueChanged, this, &AnalOptionsWidget::updateAnalPtrDepth); - connect(ui->preludeLineEdit, &QLineEdit::textChanged, this, &AnalOptionsWidget::updateAnalPrelude); + connect(ui->preludeLineEdit, &QLineEdit::textChanged, this, + &AnalOptionsWidget::updateAnalPrelude); updateAnalOptionsFromVars(); } @@ -65,11 +64,13 @@ void AnalOptionsWidget::checkboxEnabler(QCheckBox *checkBox, const QString &conf void AnalOptionsWidget::updateAnalOptionsFromVars() { for (ConfigCheckbox &confCheckbox : checkboxes) { - qhelpers::setCheckedWithoutSignals(confCheckbox.checkBox, Core()->getConfigb(confCheckbox.config)); + qhelpers::setCheckedWithoutSignals(confCheckbox.checkBox, + Core()->getConfigb(confCheckbox.config)); } // Update the rest of analysis options that are not checkboxes - ui->analInComboBox->setCurrentIndex(ui->analInComboBox->findData(Core()->getConfig("analysis.in"))); + ui->analInComboBox->setCurrentIndex( + ui->analInComboBox->findData(Core()->getConfig("analysis.in"))); ui->ptrDepthSpinBox->setValue(Core()->getConfigi("analysis.ptrdepth")); ui->preludeLineEdit->setText(Core()->getConfig("analysis.prelude")); } diff --git a/src/dialogs/preferences/AnalOptionsWidget.h b/src/dialogs/preferences/AnalOptionsWidget.h index d7e8250a..fcb01ec6 100644 --- a/src/dialogs/preferences/AnalOptionsWidget.h +++ b/src/dialogs/preferences/AnalOptionsWidget.h @@ -22,20 +22,23 @@ public: private: std::unique_ptr ui; - struct ConfigCheckbox { + struct ConfigCheckbox + { QCheckBox *checkBox; QString config; }; QList checkboxes; /** - * @brief This function creates the list with the different options shown in the selector for analysis.in + * @brief This function creates the list with the different options shown in the selector for + * analysis.in */ void createAnalInOptionsList(); private slots: /** - * @brief A slot to display the options in the dialog according to the current analysis.* configuration + * @brief A slot to display the options in the dialog according to the current analysis.* + * configuration */ void updateAnalOptionsFromVars(); @@ -60,7 +63,8 @@ private slots: static void updateAnalPtrDepth(int value); /** - * @brief slot to update the value of analysis.prelude when a new value is introduced in the corresponding textbox + * @brief slot to update the value of analysis.prelude when a new value is introduced in the + * corresponding textbox * @param prelude - The new value for analysis.prelude */ static void updateAnalPrelude(const QString &prelude); diff --git a/src/dialogs/preferences/AppearanceOptionsWidget.cpp b/src/dialogs/preferences/AppearanceOptionsWidget.cpp index 1843573a..5bb38998 100644 --- a/src/dialogs/preferences/AppearanceOptionsWidget.cpp +++ b/src/dialogs/preferences/AppearanceOptionsWidget.cpp @@ -24,8 +24,7 @@ #include "widgets/ColorPicker.h" AppearanceOptionsWidget::AppearanceOptionsWidget(PreferencesDialog *dialog) - : QDialog(dialog), - ui(new Ui::AppearanceOptionsWidget) + : QDialog(dialog), ui(new Ui::AppearanceOptionsWidget) { ui->setupUi(this); updateFromConfig(); @@ -53,24 +52,21 @@ AppearanceOptionsWidget::AppearanceOptionsWidget(PreferencesDialog *dialog) connect(Config(), &Configuration::interfaceThemeChanged, this, setIcons); connect(ui->languageComboBox, - static_cast(&QComboBox::currentIndexChanged), - this, + static_cast(&QComboBox::currentIndexChanged), this, &AppearanceOptionsWidget::onLanguageComboBoxCurrentIndexChanged); connect(Config(), &Configuration::fontsUpdated, this, &AppearanceOptionsWidget::updateFontFromConfig); - connect(ui->colorComboBox, &QComboBox::currentTextChanged, - this, &AppearanceOptionsWidget::updateModificationButtons); + connect(ui->colorComboBox, &QComboBox::currentTextChanged, this, + &AppearanceOptionsWidget::updateModificationButtons); - connect(ui->fontZoomBox, - static_cast(&QSpinBox::valueChanged), - this, - &AppearanceOptionsWidget::onFontZoomBoxValueChanged); + connect(ui->fontZoomBox, static_cast(&QSpinBox::valueChanged), this, + &AppearanceOptionsWidget::onFontZoomBoxValueChanged); ui->useDecompilerHighlighter->setChecked(Config()->isDecompilerAnnotationHighlighterEnabled()); - connect(ui->useDecompilerHighlighter, &QCheckBox::toggled, - this, [](bool checked){ Config()->enableDecompilerAnnotationHighlighter(checked); }); + connect(ui->useDecompilerHighlighter, &QCheckBox::toggled, this, + [](bool checked) { Config()->enableDecompilerAnnotationHighlighter(checked); }); } AppearanceOptionsWidget::~AppearanceOptionsWidget() {} @@ -83,7 +79,8 @@ void AppearanceOptionsWidget::updateFontFromConfig() void AppearanceOptionsWidget::updateThemeFromConfig(bool interfaceThemeChanged) { - // Disconnect currentIndexChanged because clearing the comboxBox and refiling it causes its index to change. + // Disconnect currentIndexChanged because clearing the comboxBox and refiling it causes its + // index to change. QSignalBlocker signalBlockerThemeBox(ui->themeComboBox); ui->themeComboBox->clear(); @@ -102,11 +99,10 @@ void AppearanceOptionsWidget::updateThemeFromConfig(bool interfaceThemeChanged) void AppearanceOptionsWidget::onFontZoomBoxValueChanged(int zoom) { - qreal zoomFactor = zoom / 100.0; - Config()->setZoomFactor(zoomFactor); + qreal zoomFactor = zoom / 100.0; + Config()->setZoomFactor(zoomFactor); } - void AppearanceOptionsWidget::on_fontSelectionButton_clicked() { QFont currentFont = Config()->getBaseFont(); @@ -138,10 +134,9 @@ void AppearanceOptionsWidget::on_copyButton_clicked() QString newThemeName; do { - newThemeName = QInputDialog::getText(this, tr("Enter theme name"), - tr("Name:"), QLineEdit::Normal, - currColorTheme + tr(" - copy")) - .trimmed(); + newThemeName = QInputDialog::getText(this, tr("Enter theme name"), tr("Name:"), + QLineEdit::Normal, currColorTheme + tr(" - copy")) + .trimmed(); if (newThemeName.isEmpty()) { return; } @@ -165,10 +160,8 @@ void AppearanceOptionsWidget::on_deleteButton_clicked() QMessageBox::critical(nullptr, tr("Error"), ThemeWorker().deleteTheme(currTheme)); return; } - int ret = QMessageBox::question(nullptr, - tr("Delete"), - tr("Are you sure you want to delete %1?") - .arg(currTheme)); + int ret = QMessageBox::question( + nullptr, tr("Delete"), tr("Are you sure you want to delete %1?").arg(currTheme)); if (ret == QMessageBox::Yes) { QString err = ThemeWorker().deleteTheme(currTheme); updateThemeFromConfig(false); @@ -180,9 +173,8 @@ void AppearanceOptionsWidget::on_deleteButton_clicked() void AppearanceOptionsWidget::on_importButton_clicked() { - QString fileName = QFileDialog::getOpenFileName(this, - "", - QStandardPaths::writableLocation(QStandardPaths::HomeLocation)); + QString fileName = QFileDialog::getOpenFileName( + this, "", QStandardPaths::writableLocation(QStandardPaths::HomeLocation)); if (fileName.isEmpty()) { return; } @@ -190,9 +182,9 @@ void AppearanceOptionsWidget::on_importButton_clicked() QString err = ThemeWorker().importTheme(fileName); QString themeName = QFileInfo(fileName).fileName(); if (err.isEmpty()) { - QMessageBox::information(this, - tr("Success"), - tr("Color theme %1 was successfully imported.").arg(themeName)); + QMessageBox::information( + this, tr("Success"), + tr("Color theme %1 was successfully imported.").arg(themeName)); Config()->setColorTheme(themeName); updateThemeFromConfig(false); } else { @@ -203,10 +195,10 @@ void AppearanceOptionsWidget::on_importButton_clicked() void AppearanceOptionsWidget::on_exportButton_clicked() { QString theme = ui->colorComboBox->currentText(); - QString file = QFileDialog::getSaveFileName(this, - "", - QStandardPaths::writableLocation(QStandardPaths::HomeLocation) - + QDir::separator() + theme); + QString file = QFileDialog::getSaveFileName( + this, "", + QStandardPaths::writableLocation(QStandardPaths::HomeLocation) + QDir::separator() + + theme); if (file.isEmpty()) { return; } @@ -217,8 +209,7 @@ void AppearanceOptionsWidget::on_exportButton_clicked() } QString err = ThemeWorker().save(ThemeWorker().getTheme(theme), file); if (err.isEmpty()) { - QMessageBox::information(this, - tr("Success"), + QMessageBox::information(this, tr("Success"), tr("Color theme %1 was successfully exported.").arg(theme)); } else { QMessageBox::critical(this, tr("Error"), err); @@ -228,11 +219,8 @@ void AppearanceOptionsWidget::on_exportButton_clicked() void AppearanceOptionsWidget::on_renameButton_clicked() { QString currColorTheme = Config()->getColorTheme(); - QString newName = QInputDialog::getText(this, - tr("Enter new theme name"), - tr("Name:"), - QLineEdit::Normal, - currColorTheme); + QString newName = QInputDialog::getText(this, tr("Enter new theme name"), tr("Name:"), + QLineEdit::Normal, currColorTheme); if (newName.isEmpty() || newName == currColorTheme) { return; } @@ -250,8 +238,7 @@ void AppearanceOptionsWidget::onLanguageComboBoxCurrentIndexChanged(int index) { QString language = ui->languageComboBox->itemText(index).toLower(); if (Config()->setLocaleByName(language)) { - QMessageBox::information(this, - tr("Language settings"), + QMessageBox::information(this, tr("Language settings"), tr("Language will be changed after next application start.")); return; } @@ -259,7 +246,7 @@ void AppearanceOptionsWidget::onLanguageComboBoxCurrentIndexChanged(int index) qWarning() << tr("Cannot set language, not found in available ones"); } -void AppearanceOptionsWidget::updateModificationButtons(const QString& theme) +void AppearanceOptionsWidget::updateModificationButtons(const QString &theme) { bool editable = ThemeWorker().isCustomTheme(theme); ui->editButton->setEnabled(editable); @@ -274,14 +261,16 @@ void AppearanceOptionsWidget::updateFromConfig() ui->fontZoomBox->setValue(qRound(Config()->getZoomFactor() * 100)); } -QIcon AppearanceOptionsWidget::getIconFromSvg(const QString& fileName, const QColor& after, const QColor& before) +QIcon AppearanceOptionsWidget::getIconFromSvg(const QString &fileName, const QColor &after, + const QColor &before) { QFile file(fileName); if (!file.open(QIODevice::ReadOnly)) { return QIcon(); } QString data = file.readAll(); - data.replace(QRegularExpression(QString("#%1").arg(before.isValid() ? before.name().remove(0, 1) : "[0-9a-fA-F]{6}")), + data.replace(QRegularExpression(QString("#%1").arg(before.isValid() ? before.name().remove(0, 1) + : "[0-9a-fA-F]{6}")), QString("%1").arg(after.name())); QSvgRenderer svgRenderer(data.toUtf8()); diff --git a/src/dialogs/preferences/AppearanceOptionsWidget.h b/src/dialogs/preferences/AppearanceOptionsWidget.h index 71885a22..de52fb38 100644 --- a/src/dialogs/preferences/AppearanceOptionsWidget.h +++ b/src/dialogs/preferences/AppearanceOptionsWidget.h @@ -55,7 +55,7 @@ private slots: void onLanguageComboBoxCurrentIndexChanged(int index); private: - void updateModificationButtons(const QString& theme); + void updateModificationButtons(const QString &theme); void updateFromConfig(); /** @@ -68,9 +68,8 @@ private: * @param before * Color that should be repalced. */ - QIcon getIconFromSvg(const QString &fileName, const QColor &after, const QColor &before = QColor()); - + QIcon getIconFromSvg(const QString &fileName, const QColor &after, + const QColor &before = QColor()); }; - -#endif //ASMOPTIONSDIALOG_H +#endif // ASMOPTIONSDIALOG_H diff --git a/src/dialogs/preferences/AsmOptionsWidget.cpp b/src/dialogs/preferences/AsmOptionsWidget.cpp index 7621e7b4..fabd53a9 100644 --- a/src/dialogs/preferences/AsmOptionsWidget.cpp +++ b/src/dialogs/preferences/AsmOptionsWidget.cpp @@ -10,8 +10,7 @@ #include "common/Configuration.h" AsmOptionsWidget::AsmOptionsWidget(PreferencesDialog *dialog) - : QDialog(dialog), - ui(new Ui::AsmOptionsWidget) + : QDialog(dialog), ui(new Ui::AsmOptionsWidget) { ui->setupUi(this); @@ -21,32 +20,29 @@ AsmOptionsWidget::AsmOptionsWidget(PreferencesDialog *dialog) ui->syntaxComboBox->addItem(syntax, syntax); ui->syntaxComboBox->blockSignals(false); - checkboxes = { - { ui->describeCheckBox, "asm.describe" }, - { ui->refptrCheckBox, "asm.refptr" }, - { ui->xrefCheckBox, "asm.xrefs" }, - { ui->bblineCheckBox, "asm.bb.line" }, - { ui->varsubCheckBox, "asm.sub.var" }, - { ui->varsubOnlyCheckBox, "asm.sub.varonly" }, - { ui->lbytesCheckBox, "asm.lbytes" }, - { ui->bytespaceCheckBox, "asm.bytes.space" }, - { ui->bytesCheckBox, "asm.bytes" }, - { ui->xrefCheckBox, "asm.xrefs" }, - { ui->indentCheckBox, "asm.indent" }, - { ui->offsetCheckBox, "asm.offset" }, - { ui->relOffsetCheckBox, "asm.reloff" }, - { ui->relOffFlagsCheckBox, "asm.reloff.flags" }, - { ui->slowCheckBox, "asm.slow" }, - { ui->linesCheckBox, "asm.lines" }, - { ui->fcnlinesCheckBox, "asm.lines.fcn" }, - { ui->flgoffCheckBox, "asm.flags.offset" }, - { ui->emuCheckBox, "asm.emu" }, - { ui->emuStrCheckBox, "emu.str" }, - { ui->varsumCheckBox, "asm.var.summary" }, - { ui->sizeCheckBox, "asm.size" }, - { ui->realnameCheckBox, "asm.flags.real" } - }; - + checkboxes = { { ui->describeCheckBox, "asm.describe" }, + { ui->refptrCheckBox, "asm.refptr" }, + { ui->xrefCheckBox, "asm.xrefs" }, + { ui->bblineCheckBox, "asm.bb.line" }, + { ui->varsubCheckBox, "asm.sub.var" }, + { ui->varsubOnlyCheckBox, "asm.sub.varonly" }, + { ui->lbytesCheckBox, "asm.lbytes" }, + { ui->bytespaceCheckBox, "asm.bytes.space" }, + { ui->bytesCheckBox, "asm.bytes" }, + { ui->xrefCheckBox, "asm.xrefs" }, + { ui->indentCheckBox, "asm.indent" }, + { ui->offsetCheckBox, "asm.offset" }, + { ui->relOffsetCheckBox, "asm.reloff" }, + { ui->relOffFlagsCheckBox, "asm.reloff.flags" }, + { ui->slowCheckBox, "asm.slow" }, + { ui->linesCheckBox, "asm.lines" }, + { ui->fcnlinesCheckBox, "asm.lines.fcn" }, + { ui->flgoffCheckBox, "asm.flags.offset" }, + { ui->emuCheckBox, "asm.emu" }, + { ui->emuStrCheckBox, "emu.str" }, + { ui->varsumCheckBox, "asm.var.summary" }, + { ui->sizeCheckBox, "asm.size" }, + { ui->realnameCheckBox, "asm.flags.real" } }; QList::iterator confCheckbox; @@ -54,23 +50,26 @@ AsmOptionsWidget::AsmOptionsWidget(PreferencesDialog *dialog) for (confCheckbox = checkboxes.begin(); confCheckbox != checkboxes.end(); ++confCheckbox) { QString val = confCheckbox->config; QCheckBox &cb = *confCheckbox->checkBox; - connect(confCheckbox->checkBox, &QCheckBox::stateChanged, [this, val, &cb]() { checkboxEnabler(&cb, val) ;}); + connect(confCheckbox->checkBox, &QCheckBox::stateChanged, + [this, val, &cb]() { checkboxEnabler(&cb, val); }); } using indexSignalType = void (QComboBox::*)(int); - connect(ui->commentsComboBox, static_cast(&QComboBox::currentIndexChanged), this, - &AsmOptionsWidget::commentsComboBoxChanged); + connect(ui->commentsComboBox, static_cast(&QComboBox::currentIndexChanged), + this, &AsmOptionsWidget::commentsComboBoxChanged); connect(ui->asmComboBox, static_cast(&QComboBox::currentIndexChanged), this, - &AsmOptionsWidget::asmComboBoxChanged); - connect(ui->offsetCheckBox, &QCheckBox::toggled, this, &AsmOptionsWidget::offsetCheckBoxToggled); - connect(ui->relOffsetCheckBox, &QCheckBox::toggled, this, &AsmOptionsWidget::relOffCheckBoxToggled); - connect(Core(), &CutterCore::asmOptionsChanged, this, &AsmOptionsWidget::updateAsmOptionsFromVars); + &AsmOptionsWidget::asmComboBoxChanged); + connect(ui->offsetCheckBox, &QCheckBox::toggled, this, + &AsmOptionsWidget::offsetCheckBoxToggled); + connect(ui->relOffsetCheckBox, &QCheckBox::toggled, this, + &AsmOptionsWidget::relOffCheckBoxToggled); + connect(Core(), &CutterCore::asmOptionsChanged, this, + &AsmOptionsWidget::updateAsmOptionsFromVars); updateAsmOptionsFromVars(); } AsmOptionsWidget::~AsmOptionsWidget() {} - void AsmOptionsWidget::updateAsmOptionsFromVars() { bool cmtRightEnabled = Config()->getConfigBool("asm.cmt.right"); @@ -79,10 +78,12 @@ void AsmOptionsWidget::updateAsmOptionsFromVars() ui->cmtcolSpinBox->blockSignals(false); ui->cmtcolSpinBox->setEnabled(cmtRightEnabled); - bool offsetsEnabled = Config()->getConfigBool("asm.offset") || Config()->getConfigBool("graph.offset"); + bool offsetsEnabled = + Config()->getConfigBool("asm.offset") || Config()->getConfigBool("graph.offset"); ui->relOffsetLabel->setEnabled(offsetsEnabled); ui->relOffsetCheckBox->setEnabled(offsetsEnabled); - ui->relOffFlagsCheckBox->setEnabled(Config()->getConfigBool("asm.offset") && Config()->getConfigBool("asm.reloff")); + ui->relOffFlagsCheckBox->setEnabled(Config()->getConfigBool("asm.offset") + && Config()->getConfigBool("asm.reloff")); bool bytesEnabled = Config()->getConfigBool("asm.bytes"); ui->bytespaceCheckBox->setEnabled(bytesEnabled); @@ -123,14 +124,13 @@ void AsmOptionsWidget::updateAsmOptionsFromVars() ui->asmTabsOffSpinBox->setValue(Config()->getConfigInt("asm.tabs.off")); ui->asmTabsOffSpinBox->blockSignals(false); - QList::iterator confCheckbox; // Set the value for each checkbox in "checkboxes" as it exists in the configuration for (confCheckbox = checkboxes.begin(); confCheckbox != checkboxes.end(); ++confCheckbox) { - qhelpers::setCheckedWithoutSignals(confCheckbox->checkBox, Config()->getConfigBool(confCheckbox->config)); + qhelpers::setCheckedWithoutSignals(confCheckbox->checkBox, + Config()->getConfigBool(confCheckbox->config)); } - } void AsmOptionsWidget::resetToDefault() @@ -142,9 +142,11 @@ void AsmOptionsWidget::resetToDefault() void AsmOptionsWidget::triggerAsmOptionsChanged() { - disconnect(Core(), &CutterCore::asmOptionsChanged, this, &AsmOptionsWidget::updateAsmOptionsFromVars); + disconnect(Core(), &CutterCore::asmOptionsChanged, this, + &AsmOptionsWidget::updateAsmOptionsFromVars); Core()->triggerAsmOptionsChanged(); - connect(Core(), &CutterCore::asmOptionsChanged, this, &AsmOptionsWidget::updateAsmOptionsFromVars); + connect(Core(), &CutterCore::asmOptionsChanged, this, + &AsmOptionsWidget::updateAsmOptionsFromVars); } void AsmOptionsWidget::on_cmtcolSpinBox_valueChanged(int value) @@ -219,7 +221,6 @@ void AsmOptionsWidget::on_asmTabsOffSpinBox_valueChanged(int value) triggerAsmOptionsChanged(); } - void AsmOptionsWidget::on_varsubCheckBox_toggled(bool checked) { Config()->setConfig("asm.sub.var", checked); @@ -283,7 +284,7 @@ void AsmOptionsWidget::relOffCheckBoxToggled(bool checked) * @param checkBox - The checkbox which is responsible for the siganl * @param config - the configuration string to be toggled */ -void AsmOptionsWidget::checkboxEnabler(QCheckBox* checkBox, QString config) +void AsmOptionsWidget::checkboxEnabler(QCheckBox *checkBox, QString config) { Config()->setConfig(config, checkBox->isChecked()); triggerAsmOptionsChanged(); diff --git a/src/dialogs/preferences/AsmOptionsWidget.h b/src/dialogs/preferences/AsmOptionsWidget.h index 0847890a..0a3d069c 100644 --- a/src/dialogs/preferences/AsmOptionsWidget.h +++ b/src/dialogs/preferences/AsmOptionsWidget.h @@ -24,7 +24,8 @@ public: private: std::unique_ptr ui; - struct ConfigCheckbox { + struct ConfigCheckbox + { QCheckBox *checkBox; QString config; }; @@ -57,5 +58,4 @@ private slots: void checkboxEnabler(QCheckBox *checkbox, QString config); }; - -#endif //ASMOPTIONSWIDGET_H +#endif // ASMOPTIONSWIDGET_H diff --git a/src/dialogs/preferences/ColorThemeEditDialog.cpp b/src/dialogs/preferences/ColorThemeEditDialog.cpp index fb787a35..93838698 100644 --- a/src/dialogs/preferences/ColorThemeEditDialog.cpp +++ b/src/dialogs/preferences/ColorThemeEditDialog.cpp @@ -11,18 +11,15 @@ #include #include -ColorThemeEditDialog::ColorThemeEditDialog(QWidget *parent) : - QDialog(parent), - ui(new Ui::ColorThemeEditDialog), - configSignalBlocker(Config()), // Blocks signals from Config to avoid updating of widgets during editing - colorTheme(Config()->getColorTheme()) +ColorThemeEditDialog::ColorThemeEditDialog(QWidget *parent) + : QDialog(parent), + ui(new Ui::ColorThemeEditDialog), + configSignalBlocker( + Config()), // Blocks signals from Config to avoid updating of widgets during editing + colorTheme(Config()->getColorTheme()) { - showAlphaOptions = { - "gui.overview.border", - "gui.overview.fill", - "wordHighlight", - "lineHighlight" - }; + showAlphaOptions = { "gui.overview.border", "gui.overview.fill", "wordHighlight", + "lineHighlight" }; ui->setupUi(this); ui->colorComboBox->setShowOnlyCustom(true); @@ -39,31 +36,31 @@ ColorThemeEditDialog::ColorThemeEditDialog(QWidget *parent) : previewDisasmWidget->setFeatures(QDockWidget::NoDockWidgetFeatures); ui->colorPickerAndPreviewLayout->addWidget(previewDisasmWidget); + connect(ui->colorThemeListView, &ColorThemeListView::blink, previewDisasmWidget, + &DisassemblyWidget::colorsUpdatedSlot); - connect(ui->colorThemeListView, &ColorThemeListView::blink, - previewDisasmWidget, &DisassemblyWidget::colorsUpdatedSlot); + connect(ui->colorThemeListView, &ColorThemeListView::itemChanged, this, + [this](const QColor &color) { + ui->colorPicker->updateColor(color); + QString optionName = ui->colorThemeListView->currentIndex() + .data(Qt::UserRole) + .value() + .optionName; + ui->colorPicker->setAlphaEnabled(showAlphaOptions.contains(optionName)); + }); - connect(ui->colorThemeListView, &ColorThemeListView::itemChanged, - this, [this](const QColor& color) { - ui->colorPicker->updateColor(color); - QString optionName = ui->colorThemeListView->currentIndex() - .data(Qt::UserRole) - .value() - .optionName; - ui->colorPicker->setAlphaEnabled(showAlphaOptions.contains(optionName)); - }); - - connect(ui->filterLineEdit, &QLineEdit::textChanged, this, - [this](const QString& s) { - static_cast(ui->colorThemeListView->model())->setFilterFixedString(s); + connect(ui->filterLineEdit, &QLineEdit::textChanged, this, [this](const QString &s) { + static_cast(ui->colorThemeListView->model()) + ->setFilterFixedString(s); }); ui->colorThemeListView->setCurrentIndex(ui->colorThemeListView->model()->index(0, 0)); - connect(ui->colorPicker, &ColorPicker::colorChanged, this, &ColorThemeEditDialog::colorOptionChanged); + connect(ui->colorPicker, &ColorPicker::colorChanged, this, + &ColorThemeEditDialog::colorOptionChanged); - connect(ui->colorComboBox, &ColorThemeComboBox::currentTextChanged, - this, &ColorThemeEditDialog::editThemeChanged); + connect(ui->colorComboBox, &ColorThemeComboBox::currentTextChanged, this, + &ColorThemeEditDialog::editThemeChanged); } ColorThemeEditDialog::~ColorThemeEditDialog() @@ -92,11 +89,11 @@ void ColorThemeEditDialog::accept() void ColorThemeEditDialog::reject() { - if (themeWasEdited(ui->colorComboBox->currentText()) && - QMessageBox::question(this, - tr("Unsaved changes"), - tr("Are you sure you want to exit without saving? " - "All changes will be lost.")) == QMessageBox::No) { + if (themeWasEdited(ui->colorComboBox->currentText()) + && QMessageBox::question(this, tr("Unsaved changes"), + tr("Are you sure you want to exit without saving? " + "All changes will be lost.")) + == QMessageBox::No) { return; } configSignalBlocker.unblock(); @@ -121,7 +118,7 @@ void ColorThemeEditDialog::keyPressEvent(QKeyEvent *event) } } -void ColorThemeEditDialog::colorOptionChanged(const QColor& newColor) +void ColorThemeEditDialog::colorOptionChanged(const QColor &newColor) { QModelIndex currIndex = ui->colorThemeListView->currentIndex(); @@ -141,13 +138,12 @@ void ColorThemeEditDialog::colorOptionChanged(const QColor& newColor) previewDisasmWidget->colorsUpdatedSlot(); } -void ColorThemeEditDialog::editThemeChanged(const QString& newTheme) +void ColorThemeEditDialog::editThemeChanged(const QString &newTheme) { if (themeWasEdited(colorTheme)) { - int ret = QMessageBox::question(this, - tr("Unsaved changes"), - tr("Are you sure you want to exit without saving? " - "All changes will be lost.")); + int ret = QMessageBox::question(this, tr("Unsaved changes"), + tr("Are you sure you want to exit without saving? " + "All changes will be lost.")); if (ret == QMessageBox::No) { QSignalBlocker s(ui->colorComboBox); // avoid second call of this func int index = ui->colorComboBox->findText(colorTheme); @@ -163,7 +159,7 @@ void ColorThemeEditDialog::editThemeChanged(const QString& newTheme) setWindowTitle(tr("Theme Editor - <%1>").arg(colorTheme)); } -bool ColorThemeEditDialog::themeWasEdited(const QString& theme) const +bool ColorThemeEditDialog::themeWasEdited(const QString &theme) const { auto model = ui->colorThemeListView->colorSettingsModel(); return ThemeWorker().getTheme(theme) != model->getTheme(); diff --git a/src/dialogs/preferences/DebugOptionsWidget.cpp b/src/dialogs/preferences/DebugOptionsWidget.cpp index e40d2876..48c0c1a7 100644 --- a/src/dialogs/preferences/DebugOptionsWidget.cpp +++ b/src/dialogs/preferences/DebugOptionsWidget.cpp @@ -11,15 +11,14 @@ #include "common/Configuration.h" DebugOptionsWidget::DebugOptionsWidget(PreferencesDialog *dialog) - : QDialog(dialog), - ui(new Ui::DebugOptionsWidget) + : QDialog(dialog), ui(new Ui::DebugOptionsWidget) { ui->setupUi(this); updateDebugPlugin(); - connect(ui->pluginComboBox, &QComboBox::currentTextChanged, - this, &DebugOptionsWidget::onDebugPluginChanged); + connect(ui->pluginComboBox, &QComboBox::currentTextChanged, this, + &DebugOptionsWidget::onDebugPluginChanged); } DebugOptionsWidget::~DebugOptionsWidget() {} @@ -27,8 +26,8 @@ DebugOptionsWidget::~DebugOptionsWidget() {} void DebugOptionsWidget::updateDebugPlugin() { ui->esilBreakOnInvalid->setChecked(Config()->getConfigBool("esil.breakoninvalid")); - disconnect(ui->pluginComboBox, &QComboBox::currentTextChanged, - this, &DebugOptionsWidget::onDebugPluginChanged); + disconnect(ui->pluginComboBox, &QComboBox::currentTextChanged, this, + &DebugOptionsWidget::onDebugPluginChanged); QStringList plugins = Core()->getDebugPlugins(); for (const QString &str : plugins) @@ -37,8 +36,8 @@ void DebugOptionsWidget::updateDebugPlugin() QString plugin = Core()->getActiveDebugPlugin(); ui->pluginComboBox->setCurrentText(plugin); - connect(ui->pluginComboBox, &QComboBox::currentTextChanged, - this, &DebugOptionsWidget::onDebugPluginChanged); + connect(ui->pluginComboBox, &QComboBox::currentTextChanged, this, + &DebugOptionsWidget::onDebugPluginChanged); QString stackSize = Core()->getConfig("esil.stack.size"); ui->stackSize->setText(stackSize); diff --git a/src/dialogs/preferences/GraphOptionsWidget.cpp b/src/dialogs/preferences/GraphOptionsWidget.cpp index 9d07a845..e3980d09 100644 --- a/src/dialogs/preferences/GraphOptionsWidget.cpp +++ b/src/dialogs/preferences/GraphOptionsWidget.cpp @@ -10,36 +10,38 @@ #include "common/Configuration.h" GraphOptionsWidget::GraphOptionsWidget(PreferencesDialog *dialog) - : QDialog(dialog), - ui(new Ui::GraphOptionsWidget) + : QDialog(dialog), ui(new Ui::GraphOptionsWidget) { ui->setupUi(this); ui->checkTransparent->setChecked(Config()->getBitmapTransparentState()); ui->blockEntryCheckBox->setChecked(Config()->getGraphBlockEntryOffset()); - ui->bitmapGraphScale->setValue(Config()->getBitmapExportScaleFactor()*100.0); + ui->bitmapGraphScale->setValue(Config()->getBitmapExportScaleFactor() * 100.0); updateOptionsFromVars(); - connect(ui->bitmapGraphScale, (&QDoubleSpinBox::valueChanged), this, &GraphOptionsWidget::bitmapGraphScaleValueChanged); - connect(ui->checkTransparent, &QCheckBox::stateChanged, this, &GraphOptionsWidget::checkTransparentStateChanged); - connect(ui->blockEntryCheckBox, &QCheckBox::stateChanged, this, &GraphOptionsWidget::checkGraphBlockEntryOffsetChanged); + connect(ui->bitmapGraphScale, (&QDoubleSpinBox::valueChanged), + this, + &GraphOptionsWidget::bitmapGraphScaleValueChanged); + connect(ui->checkTransparent, &QCheckBox::stateChanged, this, + &GraphOptionsWidget::checkTransparentStateChanged); + connect(ui->blockEntryCheckBox, &QCheckBox::stateChanged, this, + &GraphOptionsWidget::checkGraphBlockEntryOffsetChanged); - connect(Core(), &CutterCore::graphOptionsChanged, this, &GraphOptionsWidget::updateOptionsFromVars); - QSpinBox* graphSpacingWidgets[] = { - ui->horizontalEdgeSpacing, ui->horizontalBlockSpacing, - ui->verticalEdgeSpacing, ui->verticalBlockSpacing - }; - for (auto widget: graphSpacingWidgets) { - connect(widget, &QSpinBox::valueChanged, - this, &GraphOptionsWidget::layoutSpacingChanged); + connect(Core(), &CutterCore::graphOptionsChanged, this, + &GraphOptionsWidget::updateOptionsFromVars); + QSpinBox *graphSpacingWidgets[] = { ui->horizontalEdgeSpacing, ui->horizontalBlockSpacing, + ui->verticalEdgeSpacing, ui->verticalBlockSpacing }; + for (auto widget : graphSpacingWidgets) { + connect(widget, &QSpinBox::valueChanged, this, + &GraphOptionsWidget::layoutSpacingChanged); } } GraphOptionsWidget::~GraphOptionsWidget() {} - void GraphOptionsWidget::updateOptionsFromVars() { - qhelpers::setCheckedWithoutSignals(ui->graphOffsetCheckBox, Config()->getConfigBool("graph.offset")); + qhelpers::setCheckedWithoutSignals(ui->graphOffsetCheckBox, + Config()->getConfigBool("graph.offset")); ui->maxColsSpinBox->blockSignals(true); ui->maxColsSpinBox->setValue(Config()->getGraphBlockMaxChars()); ui->maxColsSpinBox->blockSignals(false); @@ -54,12 +56,13 @@ void GraphOptionsWidget::updateOptionsFromVars() ui->verticalEdgeSpacing->setValue(edgeSpacing.y()); } - void GraphOptionsWidget::triggerOptionsChanged() { - disconnect(Core(), &CutterCore::graphOptionsChanged, this, &GraphOptionsWidget::updateOptionsFromVars); + disconnect(Core(), &CutterCore::graphOptionsChanged, this, + &GraphOptionsWidget::updateOptionsFromVars); Core()->triggerGraphOptionsChanged(); - connect(Core(), &CutterCore::graphOptionsChanged, this, &GraphOptionsWidget::updateOptionsFromVars); + connect(Core(), &CutterCore::graphOptionsChanged, this, + &GraphOptionsWidget::updateOptionsFromVars); } void GraphOptionsWidget::on_maxColsSpinBox_valueChanged(int value) @@ -88,14 +91,14 @@ void GraphOptionsWidget::checkTransparentStateChanged(int checked) void GraphOptionsWidget::bitmapGraphScaleValueChanged(double value) { - double value_decimal = value/(double)100.0; + double value_decimal = value / (double)100.0; Config()->setBitmapExportScaleFactor(value_decimal); } void GraphOptionsWidget::layoutSpacingChanged() { - QPoint blockSpacing{ui->horizontalBlockSpacing->value(), ui->verticalBlockSpacing->value()}; - QPoint edgeSpacing{ui->horizontalEdgeSpacing->value(), ui->verticalEdgeSpacing->value()}; + QPoint blockSpacing { ui->horizontalBlockSpacing->value(), ui->verticalBlockSpacing->value() }; + QPoint edgeSpacing { ui->horizontalEdgeSpacing->value(), ui->verticalEdgeSpacing->value() }; Config()->setGraphSpacing(blockSpacing, edgeSpacing); triggerOptionsChanged(); } diff --git a/src/dialogs/preferences/GraphOptionsWidget.h b/src/dialogs/preferences/GraphOptionsWidget.h index 300f915e..7b69dd19 100644 --- a/src/dialogs/preferences/GraphOptionsWidget.h +++ b/src/dialogs/preferences/GraphOptionsWidget.h @@ -21,6 +21,7 @@ class GraphOptionsWidget : public QDialog public: explicit GraphOptionsWidget(PreferencesDialog *dialog); ~GraphOptionsWidget(); + private: std::unique_ptr ui; @@ -39,5 +40,4 @@ private slots: void layoutSpacingChanged(); }; - -#endif //GRAPHOPTIONSWIDGET_H +#endif // GRAPHOPTIONSWIDGET_H diff --git a/src/dialogs/preferences/InitializationFileEditor.cpp b/src/dialogs/preferences/InitializationFileEditor.cpp index 0356e722..6bd31c80 100644 --- a/src/dialogs/preferences/InitializationFileEditor.cpp +++ b/src/dialogs/preferences/InitializationFileEditor.cpp @@ -16,29 +16,32 @@ #include "common/Configuration.h" InitializationFileEditor::InitializationFileEditor(PreferencesDialog *dialog) - : QDialog(dialog), - ui(new Ui::InitializationFileEditor) + : QDialog(dialog), ui(new Ui::InitializationFileEditor) { ui->setupUi(this); connect(ui->saveRC, &QDialogButtonBox::accepted, this, &InitializationFileEditor::saveCutterRC); - connect(ui->executeNow, &QDialogButtonBox::accepted, this, &InitializationFileEditor::executeCutterRC); - connect(ui->ConfigFileEdit, &QPlainTextEdit::modificationChanged, ui->saveRC, &QWidget::setEnabled); + connect(ui->executeNow, &QDialogButtonBox::accepted, this, + &InitializationFileEditor::executeCutterRC); + connect(ui->ConfigFileEdit, &QPlainTextEdit::modificationChanged, ui->saveRC, + &QWidget::setEnabled); const QDir cutterRCDirectory = Core()->getCutterRCDefaultDirectory(); auto cutterRCFileInfo = QFileInfo(cutterRCDirectory, "rc"); QString cutterRCLocation = cutterRCFileInfo.absoluteFilePath(); - + ui->cutterRCLoaded->setTextInteractionFlags(Qt::TextBrowserInteraction); ui->cutterRCLoaded->setOpenExternalLinks(true); - ui->cutterRCLoaded->setText(tr("Script is loaded from %2") - .arg(QUrl::fromLocalFile(cutterRCDirectory.absolutePath()).toString(), cutterRCLocation.toHtmlEscaped())); - + ui->cutterRCLoaded->setText( + tr("Script is loaded from %2") + .arg(QUrl::fromLocalFile(cutterRCDirectory.absolutePath()).toString(), + cutterRCLocation.toHtmlEscaped())); + ui->executeNow->button(QDialogButtonBox::Retry)->setText("Execute"); ui->ConfigFileEdit->clear(); - if(cutterRCFileInfo.exists()){ + if (cutterRCFileInfo.exists()) { QFile cutterRC(cutterRCLocation); - if(cutterRC.open(QIODevice::ReadWrite | QIODevice::Text)){ - ui->ConfigFileEdit->setPlainText(cutterRC.readAll()); + if (cutterRC.open(QIODevice::ReadWrite | QIODevice::Text)) { + ui->ConfigFileEdit->setPlainText(cutterRC.readAll()); } cutterRC.close(); } @@ -47,17 +50,17 @@ InitializationFileEditor::InitializationFileEditor(PreferencesDialog *dialog) InitializationFileEditor::~InitializationFileEditor() {}; - -void InitializationFileEditor::saveCutterRC(){ +void InitializationFileEditor::saveCutterRC() +{ const QDir cutterRCDirectory = Core()->getCutterRCDefaultDirectory(); - if(!cutterRCDirectory.exists()){ + if (!cutterRCDirectory.exists()) { cutterRCDirectory.mkpath("."); } auto cutterRCFileInfo = QFileInfo(cutterRCDirectory, "rc"); QString cutterRCLocation = cutterRCFileInfo.absoluteFilePath(); - + QFile cutterRC(cutterRCLocation); - if(cutterRC.open(QIODevice::ReadWrite | QIODevice::Truncate | QIODevice::Text)){ + if (cutterRC.open(QIODevice::ReadWrite | QIODevice::Truncate | QIODevice::Text)) { QTextStream out(&cutterRC); QString text = ui->ConfigFileEdit->toPlainText(); out << text; @@ -66,7 +69,8 @@ void InitializationFileEditor::saveCutterRC(){ ui->ConfigFileEdit->document()->setModified(false); } -void InitializationFileEditor::executeCutterRC(){ +void InitializationFileEditor::executeCutterRC() +{ saveCutterRC(); Core()->loadDefaultCutterRC(); } diff --git a/src/dialogs/preferences/InitializationFileEditor.h b/src/dialogs/preferences/InitializationFileEditor.h index b302458e..688ffb31 100644 --- a/src/dialogs/preferences/InitializationFileEditor.h +++ b/src/dialogs/preferences/InitializationFileEditor.h @@ -21,11 +21,9 @@ public: ~InitializationFileEditor(); void saveCutterRC(); void executeCutterRC(); - + private: std::unique_ptr ui; - }; - -#endif //INITIALIZATIONFILEEDITOR_H \ No newline at end of file +#endif // INITIALIZATIONFILEEDITOR_H \ No newline at end of file diff --git a/src/dialogs/preferences/PluginsOptionsWidget.cpp b/src/dialogs/preferences/PluginsOptionsWidget.cpp index bf311b53..188d8f3e 100644 --- a/src/dialogs/preferences/PluginsOptionsWidget.cpp +++ b/src/dialogs/preferences/PluginsOptionsWidget.cpp @@ -14,9 +14,7 @@ #include #include - -PluginsOptionsWidget::PluginsOptionsWidget(PreferencesDialog *dialog) - : QDialog(dialog) +PluginsOptionsWidget::PluginsOptionsWidget(PreferencesDialog *dialog) : QDialog(dialog) { auto layout = new QVBoxLayout(this); setLayout(layout); @@ -26,18 +24,14 @@ PluginsOptionsWidget::PluginsOptionsWidget(PreferencesDialog *dialog) dirLabel->setOpenExternalLinks(true); layout->addWidget(dirLabel); auto pluginPath = Plugins()->getUserPluginsDirectory(); - dirLabel->setText(tr("Plugins are loaded from %2") - .arg(QUrl::fromLocalFile(pluginPath).toString(), pluginPath.toHtmlEscaped())); + dirLabel->setText( + tr("Plugins are loaded from %2") + .arg(QUrl::fromLocalFile(pluginPath).toString(), pluginPath.toHtmlEscaped())); auto treeWidget = new QTreeWidget(this); layout->addWidget(treeWidget); treeWidget->setRootIsDecorated(false); - treeWidget->setHeaderLabels({ - tr("Name"), - tr("Description"), - tr("Version"), - tr("Author") - }); + treeWidget->setHeaderLabels({ tr("Name"), tr("Description"), tr("Version"), tr("Author") }); for (auto &plugin : Plugins()->getPlugins()) { auto item = new QTreeWidgetItem(); diff --git a/src/dialogs/preferences/PluginsOptionsWidget.h b/src/dialogs/preferences/PluginsOptionsWidget.h index 894777c3..5cca83c9 100644 --- a/src/dialogs/preferences/PluginsOptionsWidget.h +++ b/src/dialogs/preferences/PluginsOptionsWidget.h @@ -8,12 +8,11 @@ class PreferencesDialog; class PluginsOptionsWidget : public QDialog { -Q_OBJECT + Q_OBJECT public: explicit PluginsOptionsWidget(PreferencesDialog *dialog); ~PluginsOptionsWidget(); }; - -#endif //CUTTER_PLUGINSOPTIONSWIDGET_H +#endif // CUTTER_PLUGINSOPTIONSWIDGET_H diff --git a/src/dialogs/preferences/PreferenceCategory.cpp b/src/dialogs/preferences/PreferenceCategory.cpp index 81e73611..4d352d88 100644 --- a/src/dialogs/preferences/PreferenceCategory.cpp +++ b/src/dialogs/preferences/PreferenceCategory.cpp @@ -1,12 +1,12 @@ #include "PreferenceCategory.h" PreferenceCategory::PreferenceCategory(const QString &name, const QIcon &icon) - : name(name), icon(icon), widget(nullptr), children{} + : name(name), icon(icon), widget(nullptr), children {} { } PreferenceCategory::PreferenceCategory(const QString &name, QWidget *widget, const QIcon &icon) - : name(name), icon(icon), widget(widget), children{} + : name(name), icon(icon), widget(widget), children {} { } @@ -24,7 +24,7 @@ PreferenceCategory::PreferenceCategory(const QString &name, const QIcon &icon, void PreferenceCategory::addItem(QTreeWidget &tree, QStackedWidget &panel) { - QTreeWidgetItem *w = new QTreeWidgetItem({name}); + QTreeWidgetItem *w = new QTreeWidgetItem({ name }); tree.addTopLevelItem(w); for (auto &c : children) @@ -41,7 +41,7 @@ void PreferenceCategory::addItem(QTreeWidget &tree, QStackedWidget &panel) void PreferenceCategory::addItem(QTreeWidgetItem &tree, QStackedWidget &panel) { - QTreeWidgetItem *w = new QTreeWidgetItem({name}); + QTreeWidgetItem *w = new QTreeWidgetItem({ name }); tree.addChild(w); for (auto &c : children) diff --git a/src/dialogs/preferences/PreferenceCategory.h b/src/dialogs/preferences/PreferenceCategory.h index 3f777d06..b8a403ec 100644 --- a/src/dialogs/preferences/PreferenceCategory.h +++ b/src/dialogs/preferences/PreferenceCategory.h @@ -25,4 +25,4 @@ private: QList children; }; -#endif //PREFERENCECATEGORY_H +#endif // PREFERENCECATEGORY_H diff --git a/src/dialogs/preferences/PreferencesDialog.cpp b/src/dialogs/preferences/PreferencesDialog.cpp index 3a09036b..968e08f1 100644 --- a/src/dialogs/preferences/PreferencesDialog.cpp +++ b/src/dialogs/preferences/PreferencesDialog.cpp @@ -16,10 +16,8 @@ #include - PreferencesDialog::PreferencesDialog(QWidget *parent) - : QDialog(parent), - ui(new Ui::PreferencesDialog) + : QDialog(parent), ui(new Ui::PreferencesDialog) { setAttribute(Qt::WA_DeleteOnClose); ui->setupUi(this); @@ -27,65 +25,37 @@ PreferencesDialog::PreferencesDialog(QWidget *parent) QList prefs { - { - tr("Disassembly"), - new AsmOptionsWidget(this), - QIcon(":/img/icons/disas.svg"), - { - { - "Graph", - new GraphOptionsWidget(this), - QIcon(":/img/icons/graph.svg") - }, - } - }, - { - tr("Debug"), - new DebugOptionsWidget(this), - QIcon(":/img/icons/bug.svg") - }, - { - tr("Appearance"), - new AppearanceOptionsWidget(this), - QIcon(":/img/icons/polar.svg") - }, - { - tr("Plugins"), - new PluginsOptionsWidget(this), - QIcon(":/img/icons/plugins.svg") - }, - { - tr("Initialization Script"), - new InitializationFileEditor(this), - QIcon(":/img/icons/initialization.svg") - }, - { - tr("Analysis"), - new AnalOptionsWidget(this), - QIcon(":/img/icons/cog_light.svg") - } + { tr("Disassembly"), + new AsmOptionsWidget(this), + QIcon(":/img/icons/disas.svg"), + { + { "Graph", new GraphOptionsWidget(this), QIcon(":/img/icons/graph.svg") }, + } }, + { tr("Debug"), new DebugOptionsWidget(this), QIcon(":/img/icons/bug.svg") }, + { tr("Appearance"), new AppearanceOptionsWidget(this), QIcon(":/img/icons/polar.svg") }, + { tr("Plugins"), new PluginsOptionsWidget(this), QIcon(":/img/icons/plugins.svg") }, + { tr("Initialization Script"), new InitializationFileEditor(this), + QIcon(":/img/icons/initialization.svg") }, + { tr("Analysis"), new AnalOptionsWidget(this), QIcon(":/img/icons/cog_light.svg") } }; - for (auto &c : prefs) - { + for (auto &c : prefs) { c.addItem(*ui->configCategories, *ui->configPanel); } - connect(ui->configCategories, &QTreeWidget::currentItemChanged, - this, &PreferencesDialog::changePage); - connect(ui->saveButtons, &QDialogButtonBox::accepted, - this, &QWidget::close); + connect(ui->configCategories, &QTreeWidget::currentItemChanged, this, + &PreferencesDialog::changePage); + connect(ui->saveButtons, &QDialogButtonBox::accepted, this, &QWidget::close); QTreeWidgetItem *defitem = ui->configCategories->topLevelItem(0); ui->configCategories->setCurrentItem(defitem, 0); - connect(Config(), &Configuration::interfaceThemeChanged, this, &PreferencesDialog::chooseThemeIcons); + connect(Config(), &Configuration::interfaceThemeChanged, this, + &PreferencesDialog::chooseThemeIcons); chooseThemeIcons(); } -PreferencesDialog::~PreferencesDialog() -{ -} +PreferencesDialog::~PreferencesDialog() {} void PreferencesDialog::showSection(PreferencesDialog::Section section) { @@ -127,19 +97,21 @@ void PreferencesDialog::chooseThemeIcons() { QStringLiteral("Initialization Script"), QStringLiteral("initialization.svg") }, { QStringLiteral("Analysis"), QStringLiteral("cog_light.svg") }, }; - QList> supportedIconsNames; + QList> supportedIconsNames; foreach (const auto &p, kCategoryIconsNames) { - QList items = ui->configCategories->findItems(p.first, Qt::MatchContains|Qt::MatchRecursive, 0); + QList items = + ui->configCategories->findItems(p.first, Qt::MatchContains | Qt::MatchRecursive, 0); if (items.isEmpty()) { continue; } - supportedIconsNames.append( { items.first(), p.second } ); + supportedIconsNames.append({ items.first(), p.second }); } // Set the correct icon for the QAction qhelpers::setThemeIcons(supportedIconsNames, [](void *obj, const QIcon &icon) { - // here we have our setter functor, in this case it is almost "unique" because it specified the column in `setIcon` call - static_cast(obj)->setIcon(0, icon); + // here we have our setter functor, in this case it is almost "unique" because it specified + // the column in `setIcon` call + static_cast(obj)->setIcon(0, icon); }); } diff --git a/src/dialogs/preferences/PreferencesDialog.h b/src/dialogs/preferences/PreferencesDialog.h index a0acb425..c5059676 100644 --- a/src/dialogs/preferences/PreferencesDialog.h +++ b/src/dialogs/preferences/PreferencesDialog.h @@ -34,4 +34,4 @@ private: void chooseThemeIcons(); }; -#endif //PREFERENCESDIALOG_H +#endif // PREFERENCESDIALOG_H diff --git a/src/menus/AddressableItemContextMenu.cpp b/src/menus/AddressableItemContextMenu.cpp index 58a63b1b..858580c5 100644 --- a/src/menus/AddressableItemContextMenu.cpp +++ b/src/menus/AddressableItemContextMenu.cpp @@ -11,8 +11,7 @@ #include AddressableItemContextMenu::AddressableItemContextMenu(QWidget *parent, MainWindow *mainWindow) - : QMenu(parent) - , mainWindow(mainWindow) + : QMenu(parent), mainWindow(mainWindow) { actionShowInMenu = new QAction(tr("Show in"), this); actionCopyAddress = new QAction(tr("Copy address"), this); @@ -21,17 +20,17 @@ AddressableItemContextMenu::AddressableItemContextMenu(QWidget *parent, MainWind connect(actionCopyAddress, &QAction::triggered, this, &AddressableItemContextMenu::onActionCopyAddress); - actionCopyAddress->setShortcuts({Qt::CTRL + Qt::SHIFT + Qt::Key_C}); + actionCopyAddress->setShortcuts({ Qt::CTRL + Qt::SHIFT + Qt::Key_C }); actionCopyAddress->setShortcutContext(Qt::ShortcutContext::WidgetWithChildrenShortcut); connect(actionShowXrefs, &QAction::triggered, this, &AddressableItemContextMenu::onActionShowXrefs); - actionShowXrefs->setShortcut({Qt::Key_X}); + actionShowXrefs->setShortcut({ Qt::Key_X }); actionShowXrefs->setShortcutContext(Qt::ShortcutContext::WidgetWithChildrenShortcut); connect(actionAddcomment, &QAction::triggered, this, &AddressableItemContextMenu::onActionAddComment); - actionAddcomment->setShortcut({Qt::Key_Semicolon}); + actionAddcomment->setShortcut({ Qt::Key_Semicolon }); actionAddcomment->setShortcutContext(Qt::ShortcutContext::WidgetWithChildrenShortcut); addAction(actionShowInMenu); @@ -50,9 +49,7 @@ AddressableItemContextMenu::AddressableItemContextMenu(QWidget *parent, MainWind connect(this, &QMenu::aboutToShow, this, &AddressableItemContextMenu::aboutToShowSlot); } -AddressableItemContextMenu::~AddressableItemContextMenu() -{ -} +AddressableItemContextMenu::~AddressableItemContextMenu() {} void AddressableItemContextMenu::setWholeFunction(bool wholeFunciton) { @@ -119,4 +116,3 @@ void AddressableItemContextMenu::setHasTarget(bool hasTarget) action->setEnabled(hasTarget); } } - diff --git a/src/menus/AddressableItemContextMenu.h b/src/menus/AddressableItemContextMenu.h index 3d11f155..b8f4f965 100644 --- a/src/menus/AddressableItemContextMenu.h +++ b/src/menus/AddressableItemContextMenu.h @@ -26,6 +26,7 @@ public slots: void clearTarget(); signals: void xrefsTriggered(); + private: void onActionCopyAddress(); void onActionShowXrefs(); @@ -39,6 +40,7 @@ private: RVA offset; bool hasTarget = false; + protected: void setHasTarget(bool hasTarget); QAction *actionShowInMenu; diff --git a/src/menus/DecompilerContextMenu.cpp b/src/menus/DecompilerContextMenu.cpp index fcda6ae7..d43e97d2 100644 --- a/src/menus/DecompilerContextMenu.cpp +++ b/src/menus/DecompilerContextMenu.cpp @@ -16,28 +16,28 @@ #include DecompilerContextMenu::DecompilerContextMenu(QWidget *parent, MainWindow *mainWindow) - : QMenu(parent), - mainWindow(mainWindow), - curHighlightedWord(QString()), - offset(0), - decompiledFunctionAddress(RVA_INVALID), - isTogglingBreakpoints(false), - annotationHere(nullptr), - actionCopy(tr("Copy"), this), - actionCopyInstructionAddress(tr("Copy instruction address (
)"), this), - actionCopyReferenceAddress(tr("Copy address of [flag] (
)"), this), - actionShowInSubmenu(tr("Show in"), this), - actionAddComment(tr("Add Comment"), this), - actionDeleteComment(tr("Delete comment"), this), - actionRenameThingHere(tr("Rename function at cursor"), this), - actionDeleteName(tr("Delete "), this), - actionEditFunctionVariables(tr("Edit variable "), this), - actionXRefs(tr("Show X-Refs"), this), - actionToggleBreakpoint(tr("Add/remove breakpoint"), this), - actionAdvancedBreakpoint(tr("Advanced breakpoint"), this), - breakpointsInLineMenu(new QMenu(this)), - actionContinueUntil(tr("Continue until line"), this), - actionSetPC(tr("Set PC"), this) + : QMenu(parent), + mainWindow(mainWindow), + curHighlightedWord(QString()), + offset(0), + decompiledFunctionAddress(RVA_INVALID), + isTogglingBreakpoints(false), + annotationHere(nullptr), + actionCopy(tr("Copy"), this), + actionCopyInstructionAddress(tr("Copy instruction address (
)"), this), + actionCopyReferenceAddress(tr("Copy address of [flag] (
)"), this), + actionShowInSubmenu(tr("Show in"), this), + actionAddComment(tr("Add Comment"), this), + actionDeleteComment(tr("Delete comment"), this), + actionRenameThingHere(tr("Rename function at cursor"), this), + actionDeleteName(tr("Delete "), this), + actionEditFunctionVariables(tr("Edit variable "), this), + actionXRefs(tr("Show X-Refs"), this), + actionToggleBreakpoint(tr("Add/remove breakpoint"), this), + actionAdvancedBreakpoint(tr("Advanced breakpoint"), this), + breakpointsInLineMenu(new QMenu(this)), + actionContinueUntil(tr("Continue until line"), this), + actionSetPC(tr("Set PC"), this) { setActionCopy(); // Sets all three copy actions addSeparator(); @@ -61,15 +61,13 @@ DecompilerContextMenu::DecompilerContextMenu(QWidget *parent, MainWindow *mainWi setShortcutContextInActions(this); - connect(this, &DecompilerContextMenu::aboutToShow, - this, &DecompilerContextMenu::aboutToShowSlot); - connect(this, &DecompilerContextMenu::aboutToHide, - this, &DecompilerContextMenu::aboutToHideSlot); + connect(this, &DecompilerContextMenu::aboutToShow, this, + &DecompilerContextMenu::aboutToShowSlot); + connect(this, &DecompilerContextMenu::aboutToHide, this, + &DecompilerContextMenu::aboutToHideSlot); } -DecompilerContextMenu::~DecompilerContextMenu() -{ -} +DecompilerContextMenu::~DecompilerContextMenu() {} void DecompilerContextMenu::setAnnotationHere(RzCodeAnnotation *annotation) { @@ -112,8 +110,7 @@ void DecompilerContextMenu::setupBreakpointsInLineMenu() for (auto curOffset : this->availableBreakpoints) { QAction *action = breakpointsInLineMenu->addAction(RAddressString(curOffset)); connect(action, &QAction::triggered, this, [this, curOffset] { - BreakpointsDialog::editBreakpoint(Core()->getBreakpointAt(curOffset), - this); + BreakpointsDialog::editBreakpoint(Core()->getBreakpointAt(curOffset), this); }); } } @@ -122,7 +119,7 @@ void DecompilerContextMenu::setShortcutContextInActions(QMenu *menu) { for (QAction *action : menu->actions()) { if (action->isSeparator()) { - //Do nothing + // Do nothing } else if (action->menu()) { setShortcutContextInActions(action->menu()); } else { @@ -191,24 +188,26 @@ void DecompilerContextMenu::aboutToShowSlot() } else { actionAdvancedBreakpoint.setMenu(nullptr); } - actionAdvancedBreakpoint.setText(hasBreakpoint ? - tr("Edit breakpoint") : tr("Advanced breakpoint")); + actionAdvancedBreakpoint.setText(hasBreakpoint ? tr("Edit breakpoint") + : tr("Advanced breakpoint")); QString progCounterName = Core()->getRegisterName("PC").toUpper(); actionSetPC.setText(tr("Set %1 here").arg(progCounterName)); if (!annotationHere - || annotationHere->type == - RZ_CODE_ANNOTATION_TYPE_CONSTANT_VARIABLE) { // If constant, don't show rename and targeted show-in + || annotationHere->type + == RZ_CODE_ANNOTATION_TYPE_CONSTANT_VARIABLE) { // If constant, don't show rename + // and targeted show-in actionRenameThingHere.setVisible(false); copySeparator->setVisible(false); } else { copySeparator->setVisible(true); if (annotationHere->type == RZ_CODE_ANNOTATION_TYPE_FUNCTION_NAME) { - actionRenameThingHere.setText(tr("Rename function %1").arg(QString( - annotationHere->reference.name))); + actionRenameThingHere.setText( + tr("Rename function %1").arg(QString(annotationHere->reference.name))); } else if (annotationHere->type == RZ_CODE_ANNOTATION_TYPE_GLOBAL_VARIABLE) { - RzFlagItem *flagDetails = rz_flag_get_i(Core()->core()->flags, annotationHere->reference.offset); + RzFlagItem *flagDetails = + rz_flag_get_i(Core()->core()->flags, annotationHere->reference.offset); if (flagDetails) { actionRenameThingHere.setText(tr("Rename %1").arg(QString(flagDetails->name))); actionDeleteName.setText(tr("Remove %1").arg(QString(flagDetails->name))); @@ -218,20 +217,23 @@ void DecompilerContextMenu::aboutToShowSlot() } } } - actionCopyInstructionAddress.setText(tr("Copy instruction address (%1)").arg(RAddressString( - offset))); + actionCopyInstructionAddress.setText( + tr("Copy instruction address (%1)").arg(RAddressString(offset))); if (isReference()) { actionCopyReferenceAddress.setVisible(true); RVA referenceAddr = annotationHere->reference.offset; RzFlagItem *flagDetails = rz_flag_get_i(Core()->core()->flags, referenceAddr); if (annotationHere->type == RZ_CODE_ANNOTATION_TYPE_FUNCTION_NAME) { - actionCopyReferenceAddress.setText(tr("Copy address of %1 (%2)").arg - (QString(annotationHere->reference.name), RAddressString(referenceAddr))); + actionCopyReferenceAddress.setText(tr("Copy address of %1 (%2)") + .arg(QString(annotationHere->reference.name), + RAddressString(referenceAddr))); } else if (flagDetails) { - actionCopyReferenceAddress.setText(tr("Copy address of %1 (%2)").arg - (flagDetails->name, RAddressString(referenceAddr))); + actionCopyReferenceAddress.setText( + tr("Copy address of %1 (%2)") + .arg(flagDetails->name, RAddressString(referenceAddr))); } else { - actionCopyReferenceAddress.setText(tr("Copy address (%1)").arg(RAddressString(referenceAddr))); + actionCopyReferenceAddress.setText( + tr("Copy address (%1)").arg(RAddressString(referenceAddr))); } } else { actionXRefs.setVisible(false); @@ -246,9 +248,10 @@ void DecompilerContextMenu::aboutToShowSlot() if (!isFunctionVariable()) { actionEditFunctionVariables.setVisible(false); } else { - actionEditFunctionVariables.setText(tr("Edit variable %1").arg(QString( - annotationHere->variable.name))); - actionRenameThingHere.setText(tr("Rename variable %1").arg(QString(annotationHere->variable.name))); + actionEditFunctionVariables.setText( + tr("Edit variable %1").arg(QString(annotationHere->variable.name))); + actionRenameThingHere.setText( + tr("Rename variable %1").arg(QString(annotationHere->variable.name))); if (!variablePresentInRizin()) { actionEditFunctionVariables.setDisabled(true); actionRenameThingHere.setDisabled(true); @@ -272,7 +275,7 @@ void DecompilerContextMenu::setActionCopy() // Set all three copy actions connect(&actionCopyReferenceAddress, &QAction::triggered, this, &DecompilerContextMenu::actionCopyReferenceAddressTriggered); addAction(&actionCopyReferenceAddress); - actionCopyReferenceAddress.setShortcut({Qt::CTRL + Qt::SHIFT + Qt::Key_C}); + actionCopyReferenceAddress.setShortcut({ Qt::CTRL + Qt::SHIFT + Qt::Key_C }); } void DecompilerContextMenu::setActionShowInSubmenu() @@ -304,12 +307,13 @@ void DecompilerContextMenu::setActionXRefs() void DecompilerContextMenu::setActionRenameThingHere() { - actionRenameThingHere.setShortcut({Qt::Key_N}); + actionRenameThingHere.setShortcut({ Qt::Key_N }); connect(&actionRenameThingHere, &QAction::triggered, this, &DecompilerContextMenu::actionRenameThingHereTriggered); addAction(&actionRenameThingHere); - actionRenameThingHere.setToolTip(tr("Can't rename this variable.
" - "Only local variables defined in disassembly can be renamed.")); + actionRenameThingHere.setToolTip( + tr("Can't rename this variable.
" + "Only local variables defined in disassembly can be renamed.")); } void DecompilerContextMenu::setActionDeleteName() @@ -326,22 +330,23 @@ void DecompilerContextMenu::setActionEditFunctionVariables() &DecompilerContextMenu::actionEditFunctionVariablesTriggered); addAction(&actionEditFunctionVariables); actionEditFunctionVariables.setShortcut(Qt::Key_Y); - actionEditFunctionVariables.setToolTip(tr("Can't edit this variable.
" - "Only local variables defined in disassembly can be edited.")); + actionEditFunctionVariables.setToolTip( + tr("Can't edit this variable.
" + "Only local variables defined in disassembly can be edited.")); } void DecompilerContextMenu::setActionToggleBreakpoint() { connect(&actionToggleBreakpoint, &QAction::triggered, this, &DecompilerContextMenu::actionToggleBreakpointTriggered); - actionToggleBreakpoint.setShortcuts({Qt::Key_F2, Qt::CTRL + Qt::Key_B}); + actionToggleBreakpoint.setShortcuts({ Qt::Key_F2, Qt::CTRL + Qt::Key_B }); } void DecompilerContextMenu::setActionAdvancedBreakpoint() { connect(&actionAdvancedBreakpoint, &QAction::triggered, this, &DecompilerContextMenu::actionAdvancedBreakpointTriggered); - actionAdvancedBreakpoint.setShortcut({Qt::CTRL + Qt::Key_F2}); + actionAdvancedBreakpoint.setShortcut({ Qt::CTRL + Qt::Key_F2 }); } void DecompilerContextMenu::setActionContinueUntil() @@ -397,15 +402,16 @@ void DecompilerContextMenu::actionRenameThingHereTriggered() RVA func_addr = annotationHere->reference.offset; RzAnalysisFunction *func = Core()->functionAt(func_addr); if (func == NULL) { - QString function_name = QInputDialog::getText(this, - tr("Define this function at %2").arg(RAddressString(func_addr)), - tr("Function name:"), QLineEdit::Normal, currentName, &ok); + QString function_name = QInputDialog::getText( + this, tr("Define this function at %2").arg(RAddressString(func_addr)), + tr("Function name:"), QLineEdit::Normal, currentName, &ok); if (ok && !function_name.isEmpty()) { Core()->createFunctionAt(func_addr, function_name); } } else { - QString newName = QInputDialog::getText(this->mainWindow, tr("Rename function %2").arg(currentName), - tr("Function name:"), QLineEdit::Normal, currentName, &ok); + QString newName = QInputDialog::getText( + this->mainWindow, tr("Rename function %2").arg(currentName), + tr("Function name:"), QLineEdit::Normal, currentName, &ok); if (ok && !newName.isEmpty()) { Core()->renameFunction(func_addr, newName); } @@ -415,13 +421,15 @@ void DecompilerContextMenu::actionRenameThingHereTriggered() RzFlagItem *flagDetails = rz_flag_get_i(core->flags, var_addr); if (flagDetails) { QString newName = QInputDialog::getText(this, tr("Rename %2").arg(flagDetails->name), - tr("Enter name"), QLineEdit::Normal, flagDetails->name, &ok); + tr("Enter name"), QLineEdit::Normal, + flagDetails->name, &ok); if (ok && !newName.isEmpty()) { Core()->renameFlag(flagDetails->name, newName); } } else { - QString newName = QInputDialog::getText(this, tr("Add name to %2").arg(curHighlightedWord), - tr("Enter name"), QLineEdit::Normal, curHighlightedWord, &ok); + QString newName = QInputDialog::getText( + this, tr("Add name to %2").arg(curHighlightedWord), tr("Enter name"), + QLineEdit::Normal, curHighlightedWord, &ok); if (ok && !newName.isEmpty()) { Core()->addFlag(var_addr, newName, 1); } @@ -429,10 +437,11 @@ void DecompilerContextMenu::actionRenameThingHereTriggered() } else if (isFunctionVariable()) { if (!variablePresentInRizin()) { // Show can't rename this variable dialog - QMessageBox::critical(this, tr("Rename local variable %1").arg(QString( - annotationHere->variable.name)), - tr("Can't rename this variable. " - "Only local variables defined in disassembly can be renamed.")); + QMessageBox::critical( + this, + tr("Rename local variable %1").arg(QString(annotationHere->variable.name)), + tr("Can't rename this variable. " + "Only local variables defined in disassembly can be renamed.")); return; } QString oldName(annotationHere->variable.name); @@ -454,13 +463,14 @@ void DecompilerContextMenu::actionEditFunctionVariablesTriggered() if (!isFunctionVariable()) { return; } else if (!variablePresentInRizin()) { - QMessageBox::critical(this, tr("Edit local variable %1").arg(QString( - annotationHere->variable.name)), - tr("Can't edit this variable. " - "Only local variables defined in disassembly can be edited.")); + QMessageBox::critical( + this, tr("Edit local variable %1").arg(QString(annotationHere->variable.name)), + tr("Can't edit this variable. " + "Only local variables defined in disassembly can be edited.")); return; } - EditVariablesDialog dialog(decompiledFunctionAddress, QString(annotationHere->variable.name), this); + EditVariablesDialog dialog(decompiledFunctionAddress, QString(annotationHere->variable.name), + this); dialog.exec(); } @@ -470,8 +480,9 @@ void DecompilerContextMenu::actionXRefsTriggered() return; } XrefsDialog dialog(mainWindow); - QString displayString = (annotationHere->type == RZ_CODE_ANNOTATION_TYPE_FUNCTION_NAME) ? QString( - annotationHere->reference.name) : RAddressString(annotationHere->reference.offset); + QString displayString = (annotationHere->type == RZ_CODE_ANNOTATION_TYPE_FUNCTION_NAME) + ? QString(annotationHere->reference.name) + : RAddressString(annotationHere->reference.offset); dialog.fillRefsForAddress(annotationHere->reference.offset, displayString, false); dialog.exec(); } @@ -497,8 +508,8 @@ void DecompilerContextMenu::actionAdvancedBreakpointTriggered() { if (!availableBreakpoints.empty()) { // Edit the earliest breakpoint in the line - BreakpointsDialog::editBreakpoint(Core()->getBreakpointAt(this->availableBreakpoints.first()), - this); + BreakpointsDialog::editBreakpoint( + Core()->getBreakpointAt(this->availableBreakpoints.first()), this); } else { // Add a breakpoint to the earliest offset in the line BreakpointsDialog::createNewBreakpoint(this->firstOffsetInLine, this); @@ -554,7 +565,7 @@ void DecompilerContextMenu::updateTargetMenuActions() QString name; QMenu *menu; if (annotationHere->type == RZ_CODE_ANNOTATION_TYPE_GLOBAL_VARIABLE - || annotationHere->type == RZ_CODE_ANNOTATION_TYPE_CONSTANT_VARIABLE) { + || annotationHere->type == RZ_CODE_ANNOTATION_TYPE_CONSTANT_VARIABLE) { menu = mainWindow->createShowInMenu(this, annotationHere->reference.offset, MainWindow::AddressTypeHint::Data); RVA var_addr = annotationHere->reference.offset; diff --git a/src/menus/DecompilerContextMenu.h b/src/menus/DecompilerContextMenu.h index 30b042a6..7a1d5def 100644 --- a/src/menus/DecompilerContextMenu.h +++ b/src/menus/DecompilerContextMenu.h @@ -71,7 +71,8 @@ private: */ bool isTogglingBreakpoints; /** - * List of the offsets of all the breakpoints (enabled and disabled) that are present in the line under cursor. + * List of the offsets of all the breakpoints (enabled and disabled) that are present in the + * line under cursor. */ QVector availableBreakpoints; /** diff --git a/src/menus/DisassemblyContextMenu.cpp b/src/menus/DisassemblyContextMenu.cpp index f2c30277..e533d521 100644 --- a/src/menus/DisassemblyContextMenu.cpp +++ b/src/menus/DisassemblyContextMenu.cpp @@ -21,53 +21,53 @@ #include DisassemblyContextMenu::DisassemblyContextMenu(QWidget *parent, MainWindow *mainWindow) - : QMenu(parent), - offset(0), - canCopy(false), - mainWindow(mainWindow), - actionEditInstruction(this), - actionNopInstruction(this), - actionJmpReverse(this), - actionEditBytes(this), - actionCopy(this), - actionCopyAddr(this), - actionAddComment(this), - actionAnalyzeFunction(this), - actionEditFunction(this), - actionRename(this), - actionSetFunctionVarTypes(this), - actionXRefs(this), - actionXRefsForVariables(this), - actionDisplayOptions(this), - actionDeleteComment(this), - actionDeleteFlag(this), - actionDeleteFunction(this), - actionLinkType(this), - actionSetBaseBinary(this), - actionSetBaseOctal(this), - actionSetBaseDecimal(this), - actionSetBaseHexadecimal(this), - actionSetBasePort(this), - actionSetBaseIPAddr(this), - actionSetBaseSyscall(this), - actionSetBaseString(this), - actionSetBits16(this), - actionSetBits32(this), - actionSetBits64(this), - actionContinueUntil(this), - actionSetPC(this), - actionAddBreakpoint(this), - actionAdvancedBreakpoint(this), - actionSetToCode(this), - actionSetAsStringAuto(this), - actionSetAsStringRemove(this), - actionSetAsStringAdvanced(this), - actionSetToDataEx(this), - actionSetToDataByte(this), - actionSetToDataWord(this), - actionSetToDataDword(this), - actionSetToDataQword(this), - showInSubmenu(this) + : QMenu(parent), + offset(0), + canCopy(false), + mainWindow(mainWindow), + actionEditInstruction(this), + actionNopInstruction(this), + actionJmpReverse(this), + actionEditBytes(this), + actionCopy(this), + actionCopyAddr(this), + actionAddComment(this), + actionAnalyzeFunction(this), + actionEditFunction(this), + actionRename(this), + actionSetFunctionVarTypes(this), + actionXRefs(this), + actionXRefsForVariables(this), + actionDisplayOptions(this), + actionDeleteComment(this), + actionDeleteFlag(this), + actionDeleteFunction(this), + actionLinkType(this), + actionSetBaseBinary(this), + actionSetBaseOctal(this), + actionSetBaseDecimal(this), + actionSetBaseHexadecimal(this), + actionSetBasePort(this), + actionSetBaseIPAddr(this), + actionSetBaseSyscall(this), + actionSetBaseString(this), + actionSetBits16(this), + actionSetBits32(this), + actionSetBits64(this), + actionContinueUntil(this), + actionSetPC(this), + actionAddBreakpoint(this), + actionAdvancedBreakpoint(this), + actionSetToCode(this), + actionSetAsStringAuto(this), + actionSetAsStringRemove(this), + actionSetAsStringAdvanced(this), + actionSetToDataEx(this), + actionSetToDataByte(this), + actionSetToDataWord(this), + actionSetToDataDword(this), + actionSetToDataQword(this), + showInSubmenu(this) { initAction(&actionCopy, tr("Copy"), SLOT(on_actionCopy_triggered()), getCopySequence()); addAction(&actionCopy); @@ -81,23 +81,24 @@ DisassemblyContextMenu::DisassemblyContextMenu(QWidget *parent, MainWindow *main copySeparator = addSeparator(); - initAction(&actionAddComment, tr("Add Comment"), - SLOT(on_actionAddComment_triggered()), getCommentSequence()); + initAction(&actionAddComment, tr("Add Comment"), SLOT(on_actionAddComment_triggered()), + getCommentSequence()); addAction(&actionAddComment); - initAction(&actionRename, tr("Rename or add flag"), - SLOT(on_actionRename_triggered()), getRenameSequence()); + initAction(&actionRename, tr("Rename or add flag"), SLOT(on_actionRename_triggered()), + getRenameSequence()); addAction(&actionRename); initAction(&actionSetFunctionVarTypes, tr("Re-type Local Variables"), SLOT(on_actionSetFunctionVarTypes_triggered()), getRetypeSequence()); addAction(&actionSetFunctionVarTypes); - initAction(&actionEditFunction, tr("Edit function"), - SLOT(on_actionEditFunction_triggered()), getEditFunctionSequence()); + initAction(&actionEditFunction, tr("Edit function"), SLOT(on_actionEditFunction_triggered()), + getEditFunctionSequence()); addAction(&actionEditFunction); - initAction(&actionDeleteComment, tr("Delete comment"), SLOT(on_actionDeleteComment_triggered())); + initAction(&actionDeleteComment, tr("Delete comment"), + SLOT(on_actionDeleteComment_triggered())); addAction(&actionDeleteComment); initAction(&actionDeleteFlag, tr("Delete flag"), SLOT(on_actionDeleteFlag_triggered())); @@ -118,27 +119,28 @@ DisassemblyContextMenu::DisassemblyContextMenu(QWidget *parent, MainWindow *main addSetBitsMenu(); structureOffsetMenu = addMenu(tr("Structure offset")); - connect(structureOffsetMenu, &QMenu::triggered, - this, &DisassemblyContextMenu::on_actionStructureOffsetMenu_triggered); + connect(structureOffsetMenu, &QMenu::triggered, this, + &DisassemblyContextMenu::on_actionStructureOffsetMenu_triggered); - initAction(&actionLinkType, tr("Link Type to Address"), - SLOT(on_actionLinkType_triggered()), getLinkTypeSequence()); + initAction(&actionLinkType, tr("Link Type to Address"), SLOT(on_actionLinkType_triggered()), + getLinkTypeSequence()); addAction(&actionLinkType); addSetAsMenu(); addSeparator(); - initAction(&actionXRefs, tr("Show X-Refs"), - SLOT(on_actionXRefs_triggered()), getXRefSequence()); + initAction(&actionXRefs, tr("Show X-Refs"), SLOT(on_actionXRefs_triggered()), + getXRefSequence()); addAction(&actionXRefs); initAction(&actionXRefsForVariables, tr("X-Refs for local variables"), - SLOT(on_actionXRefsForVariables_triggered()), QKeySequence({Qt::SHIFT + Qt::Key_X})); + SLOT(on_actionXRefsForVariables_triggered()), + QKeySequence({ Qt::SHIFT + Qt::Key_X })); addAction(&actionXRefsForVariables); - initAction(&actionDisplayOptions, tr("Show Options"), - SLOT(on_actionDisplayOptions_triggered()), getDisplayOptionsSequence()); + initAction(&actionDisplayOptions, tr("Show Options"), SLOT(on_actionDisplayOptions_triggered()), + getDisplayOptionsSequence()); addSeparator(); @@ -158,15 +160,13 @@ DisassemblyContextMenu::DisassemblyContextMenu(QWidget *parent, MainWindow *main addSeparator(); - connect(this, &DisassemblyContextMenu::aboutToShow, - this, &DisassemblyContextMenu::aboutToShowSlot); - connect(this, &DisassemblyContextMenu::aboutToHide, - this, &DisassemblyContextMenu::aboutToHideSlot); + connect(this, &DisassemblyContextMenu::aboutToShow, this, + &DisassemblyContextMenu::aboutToShowSlot); + connect(this, &DisassemblyContextMenu::aboutToHide, this, + &DisassemblyContextMenu::aboutToHideSlot); } -DisassemblyContextMenu::~DisassemblyContextMenu() -{ -} +DisassemblyContextMenu::~DisassemblyContextMenu() {} void DisassemblyContextMenu::addSetBaseMenu() { @@ -222,25 +222,23 @@ void DisassemblyContextMenu::addSetBitsMenu() connect(&actionSetBits64, &QAction::triggered, this, [this] { setBits(64); }); } - void DisassemblyContextMenu::addSetAsMenu() { setAsMenu = addMenu(tr("Set as...")); - initAction(&actionSetToCode, tr("Code"), - SLOT(on_actionSetToCode_triggered()), getSetToCodeSequence()); + initAction(&actionSetToCode, tr("Code"), SLOT(on_actionSetToCode_triggered()), + getSetToCodeSequence()); setAsMenu->addAction(&actionSetToCode); setAsString = setAsMenu->addMenu(tr("String...")); - initAction(&actionSetAsStringAuto, tr("Auto-detect"), - SLOT(on_actionSetAsString_triggered()), getSetAsStringSequence()); + initAction(&actionSetAsStringAuto, tr("Auto-detect"), SLOT(on_actionSetAsString_triggered()), + getSetAsStringSequence()); initAction(&actionSetAsStringRemove, tr("Remove"), SLOT(on_actionSetAsStringRemove_triggered())); initAction(&actionSetAsStringAdvanced, tr("Advanced"), SLOT(on_actionSetAsStringAdvanced_triggered()), getSetAsStringAdvanced()); - setAsString->addAction(&actionSetAsStringAuto); setAsString->addAction(&actionSetAsStringRemove); setAsString->addAction(&actionSetAsStringAdvanced); @@ -268,23 +266,25 @@ void DisassemblyContextMenu::addSetToDataMenu() setToDataMenu->addAction(&actionSetToDataQword); connect(&actionSetToDataQword, &QAction::triggered, this, [this] { setToData(8); }); - initAction(&actionSetToDataEx, "...", - SLOT(on_actionSetToDataEx_triggered()), getSetToDataExSequence()); + initAction(&actionSetToDataEx, "...", SLOT(on_actionSetToDataEx_triggered()), + getSetToDataExSequence()); setToDataMenu->addAction(&actionSetToDataEx); auto switchAction = new QAction(this); - initAction(switchAction, "Switch Data", - SLOT(on_actionSetToData_triggered()), getSetToDataSequence()); + initAction(switchAction, "Switch Data", SLOT(on_actionSetToData_triggered()), + getSetToDataSequence()); } void DisassemblyContextMenu::addEditMenu() { editMenu = addMenu(tr("Edit")); - initAction(&actionEditInstruction, tr("Instruction"), SLOT(on_actionEditInstruction_triggered())); + initAction(&actionEditInstruction, tr("Instruction"), + SLOT(on_actionEditInstruction_triggered())); editMenu->addAction(&actionEditInstruction); - initAction(&actionNopInstruction, tr("Nop Instruction"), SLOT(on_actionNopInstruction_triggered())); + initAction(&actionNopInstruction, tr("Nop Instruction"), + SLOT(on_actionNopInstruction_triggered())); editMenu->addAction(&actionNopInstruction); initAction(&actionEditBytes, tr("Bytes"), SLOT(on_actionEditBytes_triggered())); @@ -302,7 +302,7 @@ void DisassemblyContextMenu::addBreakpointMenu() SLOT(on_actionAddBreakpoint_triggered()), getAddBPSequence()); breakpointMenu->addAction(&actionAddBreakpoint); initAction(&actionAdvancedBreakpoint, tr("Advanced breakpoint"), - SLOT(on_actionAdvancedBreakpoint_triggered()), QKeySequence(Qt::CTRL+Qt::Key_F2)); + SLOT(on_actionAdvancedBreakpoint_triggered()), QKeySequence(Qt::CTRL + Qt::Key_F2)); breakpointMenu->addAction(&actionAdvancedBreakpoint); } @@ -346,7 +346,7 @@ QVector DisassemblyContextMenu::getThingU } else if (typeString == "address") { type = ThingUsedHere::Type::Address; } - result.push_back(ThingUsedHere{name, offset, type}); + result.push_back(ThingUsedHere { name, offset, type }); } return result; } @@ -398,10 +398,11 @@ DisassemblyContextMenu::ThingUsedHere DisassemblyContextMenu::getThingAt(ut64 ad return tuh; } -void DisassemblyContextMenu::buildRenameMenu(ThingUsedHere* tuh) +void DisassemblyContextMenu::buildRenameMenu(ThingUsedHere *tuh) { if (!tuh) { - qWarning() << "Unexpected behavior null pointer passed to DisassemblyContextMenu::buildRenameMenu"; + qWarning() << "Unexpected behavior null pointer passed to " + "DisassemblyContextMenu::buildRenameMenu"; doRenameAction = RENAME_DO_NOTHING; return; } @@ -443,7 +444,7 @@ void DisassemblyContextMenu::setupRenaming() ThingUsedHere *tuh = nullptr; ThingUsedHere thingAt; auto things = getThingUsedHere(offset); - for (auto& thing : things) { + for (auto &thing : things) { if (thing.offset == selection || thing.name == curHighlightedWord) { // We matched something on current line tuh = &thing; @@ -456,13 +457,14 @@ void DisassemblyContextMenu::setupRenaming() thingAt = getThingAt(selection); if (thingAt.offset == 0) { - // We parsed something which resolved to 0, it's very likely nothing interesting was selected - // So we fallback on current line offset + // We parsed something which resolved to 0, it's very likely nothing interesting was + // selected So we fallback on current line offset thingAt = getThingAt(offset); } - // However, since for the moment selection selects *every* lines which match a specific offset, - // make sure we didn't want to select a local variable rather than the function itself + // However, since for the moment selection selects *every* lines which match a specific + // offset, make sure we didn't want to select a local variable rather than the function + // itself if (thingAt.type == ThingUsedHere::Type::Function) { auto vars = Core()->getVariables(offset); for (auto v : vars) { @@ -487,8 +489,8 @@ void DisassemblyContextMenu::setupRenaming() void DisassemblyContextMenu::aboutToShowSlot() { // check if set immediate base menu makes sense - QJsonObject instObject = Core()->cmdj("aoj @ " + QString::number( - offset)).array().first().toObject(); + QJsonObject instObject = + Core()->cmdj("aoj @ " + QString::number(offset)).array().first().toObject(); auto keys = instObject.keys(); bool immBase = keys.contains("val") || keys.contains("ptr"); setBaseMenu->menuAction()->setVisible(immBase); @@ -499,17 +501,16 @@ void DisassemblyContextMenu::aboutToShowSlot() QVariant memDisp; // Displacement if (instObject.contains("opex") && instObject["opex"].toObject().contains("operands")) { // Loop through both the operands of the instruction - for (const QJsonValue value: instObject["opex"].toObject()["operands"].toArray()) { + for (const QJsonValue value : instObject["opex"].toObject()["operands"].toArray()) { QJsonObject operand = value.toObject(); - if (operand.contains("type") && operand["type"].toString() == "mem" && - operand.contains("base") && !operand["base"].toString().contains("bp") && - operand.contains("disp") && operand["disp"].toVariant().toLongLong() > 0) { - - // The current operand is the one which has an immediate displacement - memBaseReg = operand["base"].toString(); - memDisp = operand["disp"].toVariant(); - break; + if (operand.contains("type") && operand["type"].toString() == "mem" + && operand.contains("base") && !operand["base"].toString().contains("bp") + && operand.contains("disp") && operand["disp"].toVariant().toLongLong() > 0) { + // The current operand is the one which has an immediate displacement + memBaseReg = operand["base"].toString(); + memDisp = operand["disp"].toVariant(); + break; } } } @@ -582,10 +583,9 @@ void DisassemblyContextMenu::aboutToShowSlot() // Only show debug options if we are currently debugging debugMenu->menuAction()->setVisible(Core()->currentlyDebugging); bool hasBreakpoint = Core()->breakpointIndexAt(offset) > -1; - actionAddBreakpoint.setText(hasBreakpoint ? - tr("Remove breakpoint") : tr("Add breakpoint")); - actionAdvancedBreakpoint.setText(hasBreakpoint ? - tr("Edit breakpoint") : tr("Advanced breakpoint")); + actionAddBreakpoint.setText(hasBreakpoint ? tr("Remove breakpoint") : tr("Add breakpoint")); + actionAdvancedBreakpoint.setText(hasBreakpoint ? tr("Edit breakpoint") + : tr("Advanced breakpoint")); QString progCounterName = Core()->getRegisterName("PC").toUpper(); actionSetPC.setText("Set " + progCounterName + " here"); @@ -615,85 +615,84 @@ QKeySequence DisassemblyContextMenu::getCopySequence() const QKeySequence DisassemblyContextMenu::getCommentSequence() const { - return {Qt::Key_Semicolon}; + return { Qt::Key_Semicolon }; } QKeySequence DisassemblyContextMenu::getCopyAddressSequence() const { - return {Qt::CTRL | Qt::SHIFT | Qt::Key_C}; + return { Qt::CTRL | Qt::SHIFT | Qt::Key_C }; } QKeySequence DisassemblyContextMenu::getSetToCodeSequence() const { - return {Qt::Key_C}; + return { Qt::Key_C }; } QKeySequence DisassemblyContextMenu::getSetAsStringSequence() const { - return {Qt::Key_A}; + return { Qt::Key_A }; } QKeySequence DisassemblyContextMenu::getSetAsStringAdvanced() const { - return {Qt::SHIFT | Qt::Key_A}; + return { Qt::SHIFT | Qt::Key_A }; } QKeySequence DisassemblyContextMenu::getSetToDataSequence() const { - return {Qt::Key_D}; + return { Qt::Key_D }; } QKeySequence DisassemblyContextMenu::getSetToDataExSequence() const { - return {Qt::Key_Asterisk}; + return { Qt::Key_Asterisk }; } QKeySequence DisassemblyContextMenu::getRenameSequence() const { - return {Qt::Key_N}; + return { Qt::Key_N }; } QKeySequence DisassemblyContextMenu::getRetypeSequence() const { - return {Qt::Key_Y}; + return { Qt::Key_Y }; } QKeySequence DisassemblyContextMenu::getXRefSequence() const { - return {Qt::Key_X}; + return { Qt::Key_X }; } QKeySequence DisassemblyContextMenu::getDisplayOptionsSequence() const { - return {}; //TODO insert correct sequence + return {}; // TODO insert correct sequence } QKeySequence DisassemblyContextMenu::getLinkTypeSequence() const { - return {Qt::Key_L}; + return { Qt::Key_L }; } QList DisassemblyContextMenu::getAddBPSequence() const { - return {Qt::Key_F2, Qt::CTRL + Qt::Key_B}; + return { Qt::Key_F2, Qt::CTRL + Qt::Key_B }; } QKeySequence DisassemblyContextMenu::getDefineNewFunctionSequence() const { - return {Qt::Key_P}; + return { Qt::Key_P }; } QKeySequence DisassemblyContextMenu::getEditFunctionSequence() const { - return {Qt::SHIFT + Qt::Key_P}; + return { Qt::SHIFT + Qt::Key_P }; } QKeySequence DisassemblyContextMenu::getUndefineFunctionSequence() const { - return {Qt::Key_U}; + return { Qt::Key_U }; } - void DisassemblyContextMenu::on_actionEditInstruction_triggered() { if (!ioModesController.prepareForWriting()) { @@ -813,8 +812,9 @@ void DisassemblyContextMenu::on_actionAnalyzeFunction_triggered() { bool ok; // Create dialog - QString functionName = QInputDialog::getText(this, tr("New function %1").arg(RAddressString(offset)), - tr("Function name:"), QLineEdit::Normal, QString(), &ok); + QString functionName = + QInputDialog::getText(this, tr("New function %1").arg(RAddressString(offset)), + tr("Function name:"), QLineEdit::Normal, QString(), &ok); // If user accepted if (ok && !functionName.isEmpty()) { @@ -826,8 +826,9 @@ void DisassemblyContextMenu::on_actionRename_triggered() { bool ok = false; if (doRenameAction == RENAME_FUNCTION) { - QString newName = QInputDialog::getText(this->mainWindow, tr("Rename function %2").arg(doRenameInfo.name), - tr("Function name:"), QLineEdit::Normal, doRenameInfo.name, &ok); + QString newName = QInputDialog::getText( + this->mainWindow, tr("Rename function %2").arg(doRenameInfo.name), + tr("Function name:"), QLineEdit::Normal, doRenameInfo.name, &ok); if (ok && !newName.isEmpty()) { Core()->renameFunction(doRenameInfo.addr, newName); } @@ -918,22 +919,21 @@ void DisassemblyContextMenu::on_actionSetAsStringAdvanced_triggered() dialog.setStringSizeValue(predictedStrSize); dialog.setStringStartAddress(offset); - if(!dialog.exec()) - { + if (!dialog.exec()) { return; } uint64_t strAddr = 0U; - if( !dialog.getStringStartAddress(strAddr) ) { - QMessageBox::critical(this->window(), tr("Wrong address"), tr("Can't edit string at this address")); + if (!dialog.getStringStartAddress(strAddr)) { + QMessageBox::critical(this->window(), tr("Wrong address"), + tr("Can't edit string at this address")); return; } CutterCore::StringTypeFormats coreStringType = CutterCore::StringTypeFormats::None; const auto strSize = dialog.getStringSizeValue(); const auto strType = dialog.getStringType(); - switch(strType) - { + switch (strType) { case EditStringDialog::StringType::Auto: coreStringType = CutterCore::StringTypeFormats::None; break; @@ -1020,7 +1020,6 @@ void DisassemblyContextMenu::on_actionEditFunction_triggered() dialog.setCallConList(callConList); dialog.setCallConSelected(fcn->cc); - if (dialog.exec()) { QString new_name = dialog.getNameText(); Core()->renameFunction(fcn->addr, new_name); @@ -1069,8 +1068,8 @@ void DisassemblyContextMenu::initAction(QAction *action, QString name, const cha } } -void DisassemblyContextMenu::initAction(QAction *action, QString name, - const char *slot, QKeySequence keySequence) +void DisassemblyContextMenu::initAction(QAction *action, QString name, const char *slot, + QKeySequence keySequence) { initAction(action, name, slot); if (keySequence.isEmpty()) { @@ -1080,8 +1079,8 @@ void DisassemblyContextMenu::initAction(QAction *action, QString name, action->setShortcutContext(Qt::WidgetWithChildrenShortcut); } -void DisassemblyContextMenu::initAction(QAction *action, QString name, - const char *slot, QList keySequenceList) +void DisassemblyContextMenu::initAction(QAction *action, QString name, const char *slot, + QList keySequenceList) { initAction(action, name, slot); if (keySequenceList.empty()) { diff --git a/src/menus/DisassemblyContextMenu.h b/src/menus/DisassemblyContextMenu.h index 921809b8..fe2f40a1 100644 --- a/src/menus/DisassemblyContextMenu.h +++ b/src/menus/DisassemblyContextMenu.h @@ -104,7 +104,6 @@ private: */ QKeySequence getLinkTypeSequence() const; - RVA offset; bool canCopy; QString curHighlightedWord; // The current highlighted word @@ -123,7 +122,6 @@ private: QAction *copySeparator; QAction actionCopyAddr; - QAction actionAddComment; QAction actionAnalyzeFunction; QAction actionEditFunction; @@ -180,7 +178,7 @@ private: QAction actionSetToDataQword; QAction showInSubmenu; - QList showTargetMenuActions; + QList showTargetMenuActions; QMenu *pluginMenu = nullptr; QAction *pluginActionMenuAction = nullptr; @@ -189,7 +187,8 @@ private: void initAction(QAction *action, QString name, const char *slot = nullptr); void initAction(QAction *action, QString name, const char *slot, QKeySequence keySequence); - void initAction(QAction *action, QString name, const char *slot, QList keySequence); + void initAction(QAction *action, QString name, const char *slot, + QList keySequence); void setBase(QString base); void setToData(int size, int repeat = 1); @@ -210,38 +209,36 @@ private: RENAME_LOCAL, RENAME_DO_NOTHING, }; - struct DoRenameInfo { + struct DoRenameInfo + { ut64 addr; QString name; }; DoRenameAction doRenameAction = RENAME_DO_NOTHING; - DoRenameInfo doRenameInfo = { }; + DoRenameInfo doRenameInfo = {}; /* * @brief Setups up the "Rename" option in the context menu * - * This function takes into account cursor location so it can choose between current address and pointed value - * i.e. `0x000040f3 lea rdi, [0x000199b1]` -> does the user want to add a flag at 0x40f3 or at 0x199b1? - * and for that we will rely on |curHighlightedWord| which is the currently selected word. + * This function takes into account cursor location so it can choose between current address and + * pointed value i.e. `0x000040f3 lea rdi, [0x000199b1]` -> does the user want to add a flag at + * 0x40f3 or at 0x199b1? and for that we will rely on |curHighlightedWord| which is the + * currently selected word. */ void setupRenaming(); /** * @brief Checks if the currently highlighted word in the disassembly widget * is a local variable or function paramter. - * @return Return true if the highlighted word is the name of a local variable or function parameter, - * return false otherwise. + * @return Return true if the highlighted word is the name of a local variable or function + * parameter, return false otherwise. */ bool isHighlightedWordLocalVar(); - struct ThingUsedHere { + struct ThingUsedHere + { QString name; RVA offset; - enum class Type { - Var, - Function, - Flag, - Address - }; + enum class Type { Var, Function, Flag, Address }; Type type; }; QVector getThingUsedHere(RVA offset); @@ -255,11 +252,11 @@ private: /* * @brief This function will set the text for the renaming menu given a ThingUsedHere * and provide information on how to handle the renaming of this specific thing. - * Indeed, selected dialogs are different when it comes to adding a flag, renaming an existing function, - * renaming a local variable... + * Indeed, selected dialogs are different when it comes to adding a flag, renaming an existing + * function, renaming a local variable... * * This function handles every possible object. */ - void buildRenameMenu(ThingUsedHere* tuh); + void buildRenameMenu(ThingUsedHere *tuh); }; #endif // DISASSEMBLYCONTEXTMENU_H diff --git a/src/plugins/PluginManager.cpp b/src/plugins/PluginManager.cpp index 837c25a4..8c2ca6c9 100644 --- a/src/plugins/PluginManager.cpp +++ b/src/plugins/PluginManager.cpp @@ -2,9 +2,9 @@ #include #ifdef CUTTER_ENABLE_PYTHON_BINDINGS -#include -#include -#include "PythonManager.h" +# include +# include +# include "PythonManager.h" #endif #include "PluginManager.h" @@ -25,13 +25,9 @@ PluginManager *PluginManager::getInstance() return uniqueInstance; } -PluginManager::PluginManager() -{ -} +PluginManager::PluginManager() {} -PluginManager::~PluginManager() -{ -} +PluginManager::~PluginManager() {} void PluginManager::loadPlugins(bool enablePlugins) { @@ -120,14 +116,13 @@ QVector PluginManager::getPluginDirectories() const QChar listSeparator = QDir::listSeparator(); #endif QString extra_plugin_dirs = CUTTER_EXTRA_PLUGIN_DIRS; - for (auto& path : extra_plugin_dirs.split(listSeparator, CUTTER_QT_SKIP_EMPTY_PARTS)) { + for (auto &path : extra_plugin_dirs.split(listSeparator, CUTTER_QT_SKIP_EMPTY_PARTS)) { result.push_back(QDir(path)); } return result; } - QString PluginManager::getUserPluginsDirectory() const { QString location = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation); @@ -154,7 +149,7 @@ void PluginManager::loadNativePlugins(const QDir &directory) } continue; } - PluginPtr cutterPlugin{qobject_cast(plugin)}; + PluginPtr cutterPlugin { qobject_cast(plugin) }; if (!cutterPlugin) { continue; } @@ -169,7 +164,8 @@ void PluginManager::loadPythonPlugins(const QDir &directory) { Python()->addPythonPath(directory.absolutePath().toLocal8Bit().data()); - for (const QString &fileName : directory.entryList(QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot)) { + for (const QString &fileName : + directory.entryList(QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot)) { if (fileName == "__pycache__") { continue; } @@ -179,7 +175,7 @@ void PluginManager::loadPythonPlugins(const QDir &directory) } else { moduleName = fileName; } - PluginPtr cutterPlugin{loadPythonPlugin(moduleName.toLocal8Bit().constData())}; + PluginPtr cutterPlugin { loadPythonPlugin(moduleName.toLocal8Bit().constData()) }; if (!cutterPlugin) { continue; } @@ -203,7 +199,8 @@ CutterPlugin *PluginManager::loadPythonPlugin(const char *moduleName) PyObject *createPluginFunc = PyObject_GetAttrString(pluginModule, "create_cutter_plugin"); if (!createPluginFunc || !PyCallable_Check(createPluginFunc)) { - qWarning() << "Plugin module does not contain create_cutter_plugin() function:" << QString(moduleName); + qWarning() << "Plugin module does not contain create_cutter_plugin() function:" + << QString(moduleName); if (createPluginFunc) { Py_DECREF(createPluginFunc); } @@ -220,9 +217,13 @@ CutterPlugin *PluginManager::loadPythonPlugin(const char *moduleName) return nullptr; } - PythonToCppFunc pythonToCpp = Shiboken::Conversions::isPythonToCppPointerConvertible(reinterpret_cast(SbkCutterBindingsTypes[SBK_CUTTERPLUGIN_IDX]), pluginObject); + PythonToCppFunc pythonToCpp = Shiboken::Conversions::isPythonToCppPointerConvertible( + reinterpret_cast(SbkCutterBindingsTypes[SBK_CUTTERPLUGIN_IDX]), + pluginObject); if (!pythonToCpp) { - qWarning() << "Plugin's create_cutter_plugin() function did not return an instance of CutterPlugin:" << QString(moduleName); + qWarning() << "Plugin's create_cutter_plugin() function did not return an instance of " + "CutterPlugin:" + << QString(moduleName); return nullptr; } CutterPlugin *plugin; diff --git a/src/plugins/PluginManager.h b/src/plugins/PluginManager.h index 1eea75a5..9e6996f1 100644 --- a/src/plugins/PluginManager.h +++ b/src/plugins/PluginManager.h @@ -9,9 +9,9 @@ #include "plugins/CutterPlugin.h" -class PluginManager: public QObject +class PluginManager : public QObject { -Q_OBJECT + Q_OBJECT public: static PluginManager *getInstance(); @@ -19,7 +19,7 @@ public: class PluginTerminator { public: - void operator()(CutterPlugin*) const; + void operator()(CutterPlugin *) const; }; using PluginPtr = std::unique_ptr; @@ -37,7 +37,7 @@ public: */ void destroyPlugins(); - const std::vector &getPlugins() { return plugins; } + const std::vector &getPlugins() { return plugins; } QVector getPluginDirectories() const; QString getUserPluginsDirectory() const; @@ -56,4 +56,4 @@ private: #define Plugins() (PluginManager::getInstance()) -#endif //PLUGINMANAGER_H +#endif // PLUGINMANAGER_H diff --git a/src/plugins/sample-cpp/CutterSamplePlugin.cpp b/src/plugins/sample-cpp/CutterSamplePlugin.cpp index aa53c889..98c95f70 100644 --- a/src/plugins/sample-cpp/CutterSamplePlugin.cpp +++ b/src/plugins/sample-cpp/CutterSamplePlugin.cpp @@ -8,9 +8,7 @@ #include "common/Configuration.h" #include "MainWindow.h" -void CutterSamplePlugin::setupPlugin() -{ -} +void CutterSamplePlugin::setupPlugin() {} void CutterSamplePlugin::setupInterface(MainWindow *main) { @@ -18,8 +16,7 @@ void CutterSamplePlugin::setupInterface(MainWindow *main) main->addPluginDockWidget(widget); } -CutterSamplePluginWidget::CutterSamplePluginWidget(MainWindow *main) : - CutterDockWidget(main) +CutterSamplePluginWidget::CutterSamplePluginWidget(MainWindow *main) : CutterDockWidget(main) { this->setObjectName("CutterSamplePluginWidget"); this->setWindowTitle("Sample C++ Plugin"); diff --git a/src/plugins/sample-cpp/CutterSamplePlugin.h b/src/plugins/sample-cpp/CutterSamplePlugin.h index 4ca971c1..114769b9 100644 --- a/src/plugins/sample-cpp/CutterSamplePlugin.h +++ b/src/plugins/sample-cpp/CutterSamplePlugin.h @@ -15,10 +15,10 @@ public: void setupPlugin() override; void setupInterface(MainWindow *main) override; - QString getName() const override { return "SamplePlugin"; } - QString getAuthor() const override { return "xarkes"; } - QString getDescription() const override { return "Just a sample plugin."; } - QString getVersion() const override { return "1.0"; } + QString getName() const override { return "SamplePlugin"; } + QString getAuthor() const override { return "xarkes"; } + QString getDescription() const override { return "Just a sample plugin."; } + QString getVersion() const override { return "1.0"; } }; class CutterSamplePluginWidget : public CutterDockWidget @@ -29,12 +29,11 @@ public: explicit CutterSamplePluginWidget(MainWindow *main, QAction *action); private: - QLabel* text; + QLabel *text; private slots: void on_seekChanged(RVA addr); void on_buttonClicked(); }; - #endif // CUTTERSAMPLEPLUGIN_H diff --git a/src/widgets/AddressableDockWidget.cpp b/src/widgets/AddressableDockWidget.cpp index 95b58270..9713fdc6 100644 --- a/src/widgets/AddressableDockWidget.cpp +++ b/src/widgets/AddressableDockWidget.cpp @@ -7,11 +7,12 @@ #include AddressableDockWidget::AddressableDockWidget(MainWindow *parent) - : CutterDockWidget(parent) - , seekable(new CutterSeekable(this)) - , syncAction(tr("Sync/unsync offset"), this) + : CutterDockWidget(parent), + seekable(new CutterSeekable(this)), + syncAction(tr("Sync/unsync offset"), this) { - connect(seekable, &CutterSeekable::syncChanged, this, &AddressableDockWidget::updateWindowTitle); + connect(seekable, &CutterSeekable::syncChanged, this, + &AddressableDockWidget::updateWindowTitle); connect(&syncAction, &QAction::triggered, seekable, &CutterSeekable::toggleSynchronization); dockMenu = new QMenu(this); diff --git a/src/widgets/AddressableItemList.h b/src/widgets/AddressableItemList.h index c007dec0..75cd832b 100644 --- a/src/widgets/AddressableItemList.h +++ b/src/widgets/AddressableItemList.h @@ -19,12 +19,11 @@ class MainWindow; template class AddressableItemList : public BaseListWidget { - static_assert (std::is_base_of::value, - "ParentModel needs to inherit from QAbstractItemModel"); + static_assert(std::is_base_of::value, + "ParentModel needs to inherit from QAbstractItemModel"); public: - explicit AddressableItemList(QWidget *parent = nullptr) : - BaseListWidget(parent) + explicit AddressableItemList(QWidget *parent = nullptr) : BaseListWidget(parent) { this->connect(this, &QWidget::customContextMenuRequested, this, &AddressableItemList::showItemContextMenu); @@ -49,10 +48,7 @@ public: this->addActions(this->getItemContextMenu()->actions()); } - AddressableItemContextMenu *getItemContextMenu() - { - return itemContextMenu; - } + AddressableItemContextMenu *getItemContextMenu() { return itemContextMenu; } void setItemContextMenu(AddressableItemContextMenu *menu) { if (itemContextMenu != menu && itemContextMenu) { @@ -60,6 +56,7 @@ public: } itemContextMenu = menu; } + protected: virtual void showItemContextMenu(const QPoint &pt) { @@ -80,10 +77,7 @@ protected: auto offset = addressableModel->address(index); Core()->seekAndShow(offset); } - virtual void onSelectedItemChanged(const QModelIndex &index) - { - updateMenuFromItem(index); - } + virtual void onSelectedItemChanged(const QModelIndex &index) { updateMenuFromItem(index); } void updateMenuFromItem(const QModelIndex &index) { if (index.isValid()) { @@ -94,6 +88,7 @@ protected: itemContextMenu->clearTarget(); } } + private: AddressableItemModelI *addressableModel = nullptr; AddressableItemContextMenu *itemContextMenu = nullptr; diff --git a/src/widgets/BacktraceWidget.cpp b/src/widgets/BacktraceWidget.cpp index 6400fb9b..bd92b3e7 100644 --- a/src/widgets/BacktraceWidget.cpp +++ b/src/widgets/BacktraceWidget.cpp @@ -5,9 +5,8 @@ #include "core/MainWindow.h" -BacktraceWidget::BacktraceWidget(MainWindow *main) : - CutterDockWidget(main), - ui(new Ui::BacktraceWidget) +BacktraceWidget::BacktraceWidget(MainWindow *main) + : CutterDockWidget(main), ui(new Ui::BacktraceWidget) { ui->setupUi(this); @@ -25,9 +24,7 @@ BacktraceWidget::BacktraceWidget(MainWindow *main) : viewBacktrace->setHorizontalScrollMode(QAbstractItemView::ScrollPerPixel); ui->verticalLayout->addWidget(viewBacktrace); - refreshDeferrer = createRefreshDeferrer([this]() { - updateContents(); - }); + refreshDeferrer = createRefreshDeferrer([this]() { updateContents(); }); connect(Core(), &CutterCore::refreshAll, this, &BacktraceWidget::updateContents); connect(Core(), &CutterCore::registersChanged, this, &BacktraceWidget::updateContents); diff --git a/src/widgets/BoolToggleDelegate.cpp b/src/widgets/BoolToggleDelegate.cpp index c07fec2c..5c80a567 100644 --- a/src/widgets/BoolToggleDelegate.cpp +++ b/src/widgets/BoolToggleDelegate.cpp @@ -1,13 +1,9 @@ #include "BoolToggleDelegate.h" #include -BoolTogggleDelegate::BoolTogggleDelegate(QObject *parent) - : QStyledItemDelegate(parent) -{ -} +BoolTogggleDelegate::BoolTogggleDelegate(QObject *parent) : QStyledItemDelegate(parent) {} -QWidget *BoolTogggleDelegate::createEditor(QWidget *parent, - const QStyleOptionViewItem &option, +QWidget *BoolTogggleDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const { if (index.data(Qt::EditRole).type() == QVariant::Bool) { diff --git a/src/widgets/BoolToggleDelegate.h b/src/widgets/BoolToggleDelegate.h index 8692baf9..d6c9c40a 100644 --- a/src/widgets/BoolToggleDelegate.h +++ b/src/widgets/BoolToggleDelegate.h @@ -10,13 +10,11 @@ class CUTTER_EXPORT BoolTogggleDelegate : public QStyledItemDelegate public: BoolTogggleDelegate(QObject *parent = nullptr); - QWidget *createEditor(QWidget *parent, - const QStyleOptionViewItem &option, + QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const override; bool editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index) override; }; - #endif // BOOLTOGGGLEDELEGATE_H diff --git a/src/widgets/BreakpointWidget.cpp b/src/widgets/BreakpointWidget.cpp index 2b449d9d..70d5b1f4 100644 --- a/src/widgets/BreakpointWidget.cpp +++ b/src/widgets/BreakpointWidget.cpp @@ -8,8 +8,7 @@ #include #include -BreakpointModel::BreakpointModel(QObject *parent) - : AddressableItemModel(parent) +BreakpointModel::BreakpointModel(QObject *parent) : AddressableItemModel(parent) { } @@ -30,7 +29,8 @@ int BreakpointModel::columnCount(const QModelIndex &) const return BreakpointModel::ColumnCount; } -static QString formatHwBreakpoint(int permission) { +static QString formatHwBreakpoint(int permission) +{ char data[] = "rwx"; if ((permission & (RZ_BP_PROT_READ | RZ_BP_PROT_ACCESS)) == 0) { data[0] = '-'; @@ -130,7 +130,7 @@ bool BreakpointModel::setData(const QModelIndex &index, const QVariant &value, i case TraceColumn: breakpoint.trace = value.toBool(); Core()->setBreakpointTrace(breakpoint.index, breakpoint.trace); - emit dataChanged(index, index, {role, Qt::DisplayRole}); + emit dataChanged(index, index, { role, Qt::DisplayRole }); return true; case EnabledColumn: breakpoint.enabled = value.toBool(); @@ -139,7 +139,7 @@ bool BreakpointModel::setData(const QModelIndex &index, const QVariant &value, i } else { Core()->disableBreakpoint(breakpoint.addr); } - emit dataChanged(index, index, {role, Qt::DisplayRole}); + emit dataChanged(index, index, { role, Qt::DisplayRole }); return true; default: return false; @@ -173,13 +173,12 @@ RVA BreakpointModel::address(const QModelIndex &index) const BreakpointProxyModel::BreakpointProxyModel(BreakpointModel *sourceModel, QObject *parent) : AddressableFilterProxyModel(sourceModel, parent) { - // Use numeric values instead of numbers converted to strings if available + // Use numeric values instead of numbers converted to strings if available this->setSortRole(Qt::EditRole); } -BreakpointWidget::BreakpointWidget(MainWindow *main) : - CutterDockWidget(main), - ui(new Ui::BreakpointWidget) +BreakpointWidget::BreakpointWidget(MainWindow *main) + : CutterDockWidget(main), ui(new Ui::BreakpointWidget) { ui->setupUi(this); @@ -190,9 +189,7 @@ BreakpointWidget::BreakpointWidget(MainWindow *main) : ui->breakpointTreeView->sortByColumn(BreakpointModel::AddrColumn, Qt::AscendingOrder); ui->breakpointTreeView->setItemDelegate(new BoolTogggleDelegate(this)); - refreshDeferrer = createRefreshDeferrer([this]() { - refreshBreakpoint(); - }); + refreshDeferrer = createRefreshDeferrer([this]() { refreshBreakpoint(); }); setScrollMode(); @@ -223,9 +220,11 @@ BreakpointWidget::BreakpointWidget(MainWindow *main) : connect(Core(), &CutterCore::commentsChanged, this, [this]() { qhelpers::emitColumnChanged(breakpointModel, BreakpointModel::CommentColumn); }); - connect(ui->addBreakpoint, &QAbstractButton::clicked, this, &BreakpointWidget::addBreakpointDialog); + connect(ui->addBreakpoint, &QAbstractButton::clicked, this, + &BreakpointWidget::addBreakpointDialog); connect(ui->delBreakpoint, &QAbstractButton::clicked, this, &BreakpointWidget::delBreakpoint); - connect(ui->delAllBreakpoints, &QAbstractButton::clicked, Core(), &CutterCore::delAllBreakpoints); + connect(ui->delAllBreakpoints, &QAbstractButton::clicked, Core(), + &CutterCore::delAllBreakpoints); } BreakpointWidget::~BreakpointWidget() = default; diff --git a/src/widgets/BreakpointWidget.h b/src/widgets/BreakpointWidget.h index 7e08e45d..80656500 100644 --- a/src/widgets/BreakpointWidget.h +++ b/src/widgets/BreakpointWidget.h @@ -16,12 +16,11 @@ namespace Ui { class BreakpointWidget; } - class MainWindow; class QTreeWidgetItem; class BreakpointWidget; -class BreakpointModel: public AddressableItemModel +class BreakpointModel : public AddressableItemModel { Q_OBJECT @@ -31,7 +30,15 @@ private: QList breakpoints; public: - enum Column { AddrColumn = 0, NameColumn, TypeColumn, TraceColumn, EnabledColumn, CommentColumn, ColumnCount }; + enum Column { + AddrColumn = 0, + NameColumn, + TypeColumn, + TraceColumn, + EnabledColumn, + CommentColumn, + ColumnCount + }; enum Role { BreakpointDescriptionRole = Qt::UserRole }; BreakpointModel(QObject *parent = nullptr); @@ -47,23 +54,17 @@ public: bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole) override; Qt::ItemFlags flags(const QModelIndex &index) const override; - RVA address(const QModelIndex &index) const override; }; - - class BreakpointProxyModel : public AddressableFilterProxyModel { Q_OBJECT public: BreakpointProxyModel(BreakpointModel *sourceModel, QObject *parent = nullptr); - }; - - class BreakpointWidget : public CutterDockWidget { Q_OBJECT diff --git a/src/widgets/CallGraph.cpp b/src/widgets/CallGraph.cpp index ddfb57f6..f1b5a955 100644 --- a/src/widgets/CallGraph.cpp +++ b/src/widgets/CallGraph.cpp @@ -7,9 +7,7 @@ #include CallGraphWidget::CallGraphWidget(MainWindow *main, bool global) - : AddressableDockWidget(main) - , graphView(new CallGraphView(this, main, global)) - , global(global) + : AddressableDockWidget(main), graphView(new CallGraphView(this, main, global)), global(global) { setObjectName(main->getUniqueObjectName("CallGraphWidget")); this->setWindowTitle(getWindowTitle()); @@ -18,9 +16,7 @@ CallGraphWidget::CallGraphWidget(MainWindow *main, bool global) setWidget(graphView); } -CallGraphWidget::~CallGraphWidget() -{ -} +CallGraphWidget::~CallGraphWidget() {} QString CallGraphWidget::getWindowTitle() const { @@ -35,9 +31,7 @@ void CallGraphWidget::onSeekChanged(RVA address) } CallGraphView::CallGraphView(CutterDockWidget *parent, MainWindow *main, bool global) - : SimpleTextGraphView(parent, main) - , global(global) - , refreshDeferrer(nullptr, this) + : SimpleTextGraphView(parent, main), global(global), refreshDeferrer(nullptr, this) { enableAddresses(true); refreshDeferrer.registerFor(parent); diff --git a/src/widgets/CallGraph.h b/src/widgets/CallGraph.h index f9c15814..8085fdcf 100644 --- a/src/widgets/CallGraph.h +++ b/src/widgets/CallGraph.h @@ -18,18 +18,19 @@ public: void showExportDialog() override; void showAddress(RVA address); void refreshView() override; + protected: bool global; ///< is this a global or function callgraph RVA address = RVA_INVALID; ///< function address if this is not a global callgraph std::unordered_map addressMapping; ///< mapping from addresses to block id void loadCurrentGraph() override; void restoreCurrentBlock() override; + private: RefreshDeferrer refreshDeferrer; RVA lastLoadedAddress = RVA_INVALID; }; - class CallGraphWidget : public AddressableDockWidget { Q_OBJECT @@ -37,8 +38,10 @@ class CallGraphWidget : public AddressableDockWidget public: explicit CallGraphWidget(MainWindow *main, bool global); ~CallGraphWidget(); + protected: QString getWindowTitle() const override; + private: CallGraphView *graphView; bool global; diff --git a/src/widgets/ClassesWidget.cpp b/src/widgets/ClassesWidget.cpp index 6b36ffe9..b20f1935 100644 --- a/src/widgets/ClassesWidget.cpp +++ b/src/widgets/ClassesWidget.cpp @@ -31,12 +31,7 @@ QVariant ClassesModel::headerData(int section, Qt::Orientation, int role) const } } - - -BinClassesModel::BinClassesModel(QObject *parent) - : ClassesModel(parent) -{ -} +BinClassesModel::BinClassesModel(QObject *parent) : ClassesModel(parent) {} void BinClassesModel::setClasses(const QList &classes) { @@ -45,14 +40,14 @@ void BinClassesModel::setClasses(const QList &classes) endResetModel(); } - QModelIndex BinClassesModel::index(int row, int column, const QModelIndex &parent) const { if (!parent.isValid()) { return createIndex(row, column, (quintptr)0); // root function nodes have id = 0 } - return createIndex(row, column, (quintptr)parent.row() + 1); // sub-nodes have id = class index + 1 + return createIndex(row, column, + (quintptr)parent.row() + 1); // sub-nodes have id = class index + 1 } QModelIndex BinClassesModel::parent(const QModelIndex &index) const @@ -102,7 +97,8 @@ QVariant BinClassesModel::data(const QModelIndex &index, int role) const } else { // method/field/base row cls = &classes.at(static_cast(index.internalId() - 1)); - if (index.row() >= cls->baseClasses.length() + cls->methods.length() + cls->fields.length()) { + if (index.row() + >= cls->baseClasses.length() + cls->methods.length() + cls->fields.length()) { return QVariant(); } @@ -181,8 +177,7 @@ QVariant BinClassesModel::data(const QModelIndex &index, int role) const default: return QVariant(); } - } - else { + } else { switch (role) { case Qt::DisplayRole: switch (index.column()) { @@ -209,14 +204,12 @@ QVariant BinClassesModel::data(const QModelIndex &index, int role) const } } - AnalClassesModel::AnalClassesModel(CutterDockWidget *parent) : ClassesModel(parent), attrs(new QMap>) { - // Just use a simple refresh deferrer. If an event was triggered in the background, simply refresh everything later. - refreshDeferrer = parent->createRefreshDeferrer([this]() { - this->refreshAll(); - }); + // Just use a simple refresh deferrer. If an event was triggered in the background, simply + // refresh everything later. + refreshDeferrer = parent->createRefreshDeferrer([this]() { this->refreshAll(); }); connect(Core(), &CutterCore::refreshAll, this, &AnalClassesModel::refreshAll); connect(Core(), &CutterCore::codeRebased, this, &AnalClassesModel::refreshAll); @@ -262,7 +255,7 @@ void AnalClassesModel::classDeleted(const QString &cls) // find the position using binary search and remove the row auto it = std::lower_bound(classes.begin(), classes.end(), cls); - if(it == classes.end() || *it != cls) { + if (it == classes.end() || *it != cls) { return; } int index = it - classes.begin(); @@ -310,19 +303,19 @@ void AnalClassesModel::classAttrsChanged(const QString &cls) } auto it = std::lower_bound(classes.begin(), classes.end(), cls); - if(it == classes.end() || *it != cls) { + if (it == classes.end() || *it != cls) { return; } QPersistentModelIndex persistentIndex = QPersistentModelIndex(index(it - classes.begin(), 0)); - layoutAboutToBeChanged({persistentIndex}); + layoutAboutToBeChanged({ persistentIndex }); attrs->remove(cls); - layoutChanged({persistentIndex}); + layoutChanged({ persistentIndex }); } const QVector &AnalClassesModel::getAttrs(const QString &cls) const { auto it = attrs->find(cls); - if(it != attrs->end()) { + if (it != attrs->end()) { return it.value(); } @@ -332,15 +325,15 @@ const QVector &AnalClassesModel::getAttrs(const QSt QList vtables = Core()->getAnalClassVTables(cls); clsAttrs.reserve(bases.size() + meths.size() + vtables.size()); - for(const AnalBaseClassDescription &base : bases) { + for (const AnalBaseClassDescription &base : bases) { clsAttrs.push_back(Attribute(Attribute::Type::Base, QVariant::fromValue(base))); } - for(const AnalVTableDescription &vtable : vtables) { + for (const AnalVTableDescription &vtable : vtables) { clsAttrs.push_back(Attribute(Attribute::Type::VTable, QVariant::fromValue(vtable))); } - for(const AnalMethodDescription &meth : meths) { + for (const AnalMethodDescription &meth : meths) { clsAttrs.push_back(Attribute(Attribute::Type::Method, QVariant::fromValue(meth))); } @@ -353,7 +346,8 @@ QModelIndex AnalClassesModel::index(int row, int column, const QModelIndex &pare return createIndex(row, column, (quintptr)0); // root function nodes have id = 0 } - return createIndex(row, column, (quintptr)parent.row() + 1); // sub-nodes have id = class index + 1 + return createIndex(row, column, + (quintptr)parent.row() + 1); // sub-nodes have id = class index + 1 } QModelIndex AnalClassesModel::parent(const QModelIndex &index) const @@ -438,7 +432,8 @@ QVariant AnalClassesModel::data(const QModelIndex &index, int role) const } case Qt::DecorationRole: if (index.column() == NAME) { - return QIcon(new SvgIconEngine(QString(":/img/icons/home.svg"), QPalette::WindowText)); + return QIcon(new SvgIconEngine(QString(":/img/icons/home.svg"), + QPalette::WindowText)); } return QVariant(); case VTableRole: @@ -464,13 +459,15 @@ QVariant AnalClassesModel::data(const QModelIndex &index, int role) const case OFFSET: return meth.addr == RVA_INVALID ? QString() : RAddressString(meth.addr); case VTABLE: - return meth.vtableOffset < 0 ? QString() : QString("+%1").arg(meth.vtableOffset); + return meth.vtableOffset < 0 ? QString() + : QString("+%1").arg(meth.vtableOffset); default: return QVariant(); } case Qt::DecorationRole: if (index.column() == NAME) { - return QIcon(new SvgIconEngine(QString(":/img/icons/fork.svg"), QPalette::WindowText)); + return QIcon(new SvgIconEngine(QString(":/img/icons/fork.svg"), + QPalette::WindowText)); } return QVariant(); case VTableRole: @@ -502,7 +499,8 @@ QVariant AnalClassesModel::data(const QModelIndex &index, int role) const } case Qt::DecorationRole: if (index.column() == NAME) { - return QIcon(new SvgIconEngine(QString(":/img/icons/list.svg"), QPalette::WindowText)); + return QIcon(new SvgIconEngine(QString(":/img/icons/list.svg"), + QPalette::WindowText)); } return QVariant(); case OffsetRole: @@ -519,9 +517,6 @@ QVariant AnalClassesModel::data(const QModelIndex &index, int role) const return QVariant(); } - - - ClassesSortFilterProxyModel::ClassesSortFilterProxyModel(QObject *parent) : QSortFilterProxyModel(parent) { @@ -573,11 +568,7 @@ bool ClassesSortFilterProxyModel::hasChildren(const QModelIndex &parent) const return !parent.isValid() || !parent.parent().isValid(); } - - -ClassesWidget::ClassesWidget(MainWindow *main) : - CutterDockWidget(main), - ui(new Ui::ClassesWidget) +ClassesWidget::ClassesWidget(MainWindow *main) : CutterDockWidget(main), ui(new Ui::ClassesWidget) { ui->setupUi(this); @@ -590,9 +581,10 @@ ClassesWidget::ClassesWidget(MainWindow *main) : ui->classSourceCombo->setCurrentIndex(1); - connect(ui->classSourceCombo, &QComboBox::currentIndexChanged, - this, &ClassesWidget::refreshClasses); - connect(ui->classesTreeView, &QTreeView::customContextMenuRequested, this, &ClassesWidget::showContextMenu); + connect(ui->classSourceCombo, &QComboBox::currentIndexChanged, this, + &ClassesWidget::refreshClasses); + connect(ui->classesTreeView, &QTreeView::customContextMenuRequested, this, + &ClassesWidget::showContextMenu); refreshClasses(); } @@ -644,7 +636,7 @@ void ClassesWidget::on_classesTreeView_doubleClicked(const QModelIndex &index) return; QVariant offsetData = index.data(ClassesModel::OffsetRole); - if(!offsetData.isValid()) { + if (!offsetData.isValid()) { return; } RVA offset = offsetData.value(); @@ -653,7 +645,7 @@ void ClassesWidget::on_classesTreeView_doubleClicked(const QModelIndex &index) void ClassesWidget::showContextMenu(const QPoint &pt) { - if(!analysis_model) { + if (!analysis_model) { // no context menu for bin classes return; } @@ -700,7 +692,8 @@ void ClassesWidget::on_seekToVTableAction_triggered() QList vtables = Core()->getAnalClassVTables(className); if (vtables.isEmpty()) { - QMessageBox::warning(this, tr("Missing VTable in class"), tr("The class %1 does not have any VTable!").arg(className)); + QMessageBox::warning(this, tr("Missing VTable in class"), + tr("The class %1 does not have any VTable!").arg(className)); return; } @@ -721,7 +714,8 @@ void ClassesWidget::on_addMethodAction_triggered() } QString className; - if (index.data(ClassesModel::TypeRole).toInt() == static_cast(ClassesModel::RowType::Class)) { + if (index.data(ClassesModel::TypeRole).toInt() + == static_cast(ClassesModel::RowType::Class)) { className = index.data(ClassesModel::NameRole).toString(); } else { className = index.parent().data(ClassesModel::NameRole).toString(); @@ -733,7 +727,9 @@ void ClassesWidget::on_addMethodAction_triggered() void ClassesWidget::on_editMethodAction_triggered() { QModelIndex index = ui->classesTreeView->selectionModel()->currentIndex(); - if (!index.isValid() || index.data(ClassesModel::TypeRole).toInt() != static_cast(ClassesModel::RowType::Method)) { + if (!index.isValid() + || index.data(ClassesModel::TypeRole).toInt() + != static_cast(ClassesModel::RowType::Method)) { return; } QString className = index.parent().data(ClassesModel::NameRole).toString(); @@ -744,8 +740,8 @@ void ClassesWidget::on_editMethodAction_triggered() void ClassesWidget::on_newClassAction_triggered() { bool ok; - QString name = QInputDialog::getText(this, tr("Create new Class"), - tr("Class Name:"), QLineEdit::Normal, QString(), &ok); + QString name = QInputDialog::getText(this, tr("Create new Class"), tr("Class Name:"), + QLineEdit::Normal, QString(), &ok); if (ok && !name.isEmpty()) { Core()->createNewClass(name); } @@ -754,11 +750,15 @@ void ClassesWidget::on_newClassAction_triggered() void ClassesWidget::on_deleteClassAction_triggered() { QModelIndex index = ui->classesTreeView->selectionModel()->currentIndex(); - if (!index.isValid() || index.data(ClassesModel::TypeRole).toInt() != static_cast(ClassesModel::RowType::Class)) { + if (!index.isValid() + || index.data(ClassesModel::TypeRole).toInt() + != static_cast(ClassesModel::RowType::Class)) { return; } QString className = index.data(ClassesModel::NameRole).toString(); - if (QMessageBox::question(this, tr("Delete Class"), tr("Are you sure you want to delete the class %1?").arg(className)) != QMessageBox::StandardButton::Yes) { + if (QMessageBox::question(this, tr("Delete Class"), + tr("Are you sure you want to delete the class %1?").arg(className)) + != QMessageBox::StandardButton::Yes) { return; } Core()->deleteClass(className); @@ -767,14 +767,16 @@ void ClassesWidget::on_deleteClassAction_triggered() void ClassesWidget::on_renameClassAction_triggered() { QModelIndex index = ui->classesTreeView->selectionModel()->currentIndex(); - if (!index.isValid() || index.data(ClassesModel::TypeRole).toInt() != static_cast(ClassesModel::RowType::Class)) { + if (!index.isValid() + || index.data(ClassesModel::TypeRole).toInt() + != static_cast(ClassesModel::RowType::Class)) { return; } QString oldName = index.data(ClassesModel::NameRole).toString(); bool ok; QString newName = QInputDialog::getText(this, tr("Rename Class %1").arg(oldName), - tr("Class name:"), QLineEdit::Normal, oldName, &ok); + tr("Class name:"), QLineEdit::Normal, oldName, &ok); if (ok && !newName.isEmpty()) { - Core()->renameClass(oldName, newName); + Core()->renameClass(oldName, newName); } } diff --git a/src/widgets/ClassesWidget.h b/src/widgets/ClassesWidget.h index 58c16d3a..206446cb 100644 --- a/src/widgets/ClassesWidget.h +++ b/src/widgets/ClassesWidget.h @@ -21,7 +21,7 @@ class ClassesWidget; /** * @brief Common abstract base class for Bin and Anal classes models */ -class ClassesModel: public QAbstractItemModel +class ClassesModel : public QAbstractItemModel { public: enum Columns { NAME = 0, TYPE, OFFSET, VTABLE, COUNT }; @@ -69,14 +69,15 @@ public: Q_DECLARE_METATYPE(ClassesModel::RowType) -class BinClassesModel: public ClassesModel +class BinClassesModel : public ClassesModel { Q_OBJECT private: QList classes; - QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const override; + QModelIndex index(int row, int column, + const QModelIndex &parent = QModelIndex()) const override; QModelIndex parent(const QModelIndex &index) const override; int rowCount(const QModelIndex &parent = QModelIndex()) const override; @@ -89,18 +90,18 @@ public: void setClasses(const QList &classes); }; - -class AnalClassesModel: public ClassesModel +class AnalClassesModel : public ClassesModel { -Q_OBJECT + Q_OBJECT private: /** * @brief List entry below a class * - * This roughly corresponds to attributes of Rizin analysis classes, which means it is not an attribute in the sense of - * a class member variable, but any kind of sub-info associated with the class. - * This struct in particular is used to provide a model for the list entries below a class. + * This roughly corresponds to attributes of Rizin analysis classes, which means it is not an + * attribute in the sense of a class member variable, but any kind of sub-info associated with + * the class. This struct in particular is used to provide a model for the list entries below a + * class. */ struct Attribute { @@ -133,7 +134,8 @@ private: const QVector &getAttrs(const QString &cls) const; - QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const override; + QModelIndex index(int row, int column, + const QModelIndex &parent = QModelIndex()) const override; QModelIndex parent(const QModelIndex &index) const override; int rowCount(const QModelIndex &parent = QModelIndex()) const override; @@ -153,8 +155,6 @@ public slots: void classAttrsChanged(const QString &cls); }; - - class ClassesSortFilterProxyModel : public QSortFilterProxyModel { Q_OBJECT @@ -168,8 +168,6 @@ protected: bool hasChildren(const QModelIndex &parent = QModelIndex()) const override; }; - - class ClassesWidget : public CutterDockWidget { Q_OBJECT @@ -204,5 +202,4 @@ private: ClassesSortFilterProxyModel *proxy_model; }; - #endif // CLASSESWIDGET_H diff --git a/src/widgets/ColorPicker.cpp b/src/widgets/ColorPicker.cpp index fd9ce087..e68004be 100644 --- a/src/widgets/ColorPicker.cpp +++ b/src/widgets/ColorPicker.cpp @@ -17,7 +17,7 @@ ColorPickArea::ColorPickArea(QWidget *parent) : ColorPickerWidget(parent) setMouseTracking(false); } -void ColorPickArea::paintEvent(QPaintEvent* event) +void ColorPickArea::paintEvent(QPaintEvent *event) { QPainter p(this); @@ -40,7 +40,7 @@ void ColorPickArea::paintEvent(QPaintEvent* event) p.end(); } -void ColorPickArea::setColor(const QColor& c) +void ColorPickArea::setColor(const QColor &c) { if (c == currColor) { return; @@ -54,22 +54,19 @@ void ColorPickArea::setColor(const QColor& c) emit colorChanged(currColor); } -ColorPickerWidget::ColorPickerWidget(QWidget* parent) : ColorPickWidgetAbstract(parent) -{ +ColorPickerWidget::ColorPickerWidget(QWidget *parent) : ColorPickWidgetAbstract(parent) {} -} - -void ColorPickerWidget::mouseReleaseEvent(QMouseEvent* event) +void ColorPickerWidget::mouseReleaseEvent(QMouseEvent *event) { mouseEvent(event); } -void ColorPickerWidget::mousePressEvent(QMouseEvent* event) +void ColorPickerWidget::mousePressEvent(QMouseEvent *event) { mouseEvent(event); } -void ColorPickerWidget::mouseMoveEvent(QMouseEvent* event) +void ColorPickerWidget::mouseMoveEvent(QMouseEvent *event) { mouseEvent(event); } @@ -79,36 +76,30 @@ QColor ColorPickArea::pointToColor(int x, int y) const QColor color; qreal h, s, v, a; currColor.getHsvF(&h, &s, &v, &a); - color.setHsvF(qreal(x) / width(), - 1.0 - qreal(y) / height(), - v, a); + color.setHsvF(qreal(x) / width(), 1.0 - qreal(y) / height(), v, a); return color; } -QPoint ColorPickArea::colorToPoint(const QColor& color) const +QPoint ColorPickArea::colorToPoint(const QColor &color) const { qreal h, s, v; color.getHsvF(&h, &s, &v); return QPointF(h * width(), (1.0 - s) * height()).toPoint(); } -void ColorPickerWidget::mouseEvent(QMouseEvent* event) +void ColorPickerWidget::mouseEvent(QMouseEvent *event) { QPoint pos = event->pos(); if (!rect().contains(pos.x(), rect().y())) { - pos.setX(rect().x() < pos.x() - ? rect().right() + 1 - : rect().x()); + pos.setX(rect().x() < pos.x() ? rect().right() + 1 : rect().x()); } if (!rect().contains(rect().x(), pos.y())) { - pos.setY(rect().y() < pos.y() - ? rect().bottom() + 1 - : rect().y()); + pos.setY(rect().y() < pos.y() ? rect().bottom() + 1 : rect().y()); } setColor(pointToColor(pos.x(), pos.y())); } -void ColorValueBar::setColor(const QColor& c) +void ColorValueBar::setColor(const QColor &c) { if (c == currColor) { return; @@ -119,7 +110,7 @@ void ColorValueBar::setColor(const QColor& c) emit colorChanged(currColor); } -void ColorValueBar::paintEvent(QPaintEvent* event) +void ColorValueBar::paintEvent(QPaintEvent *event) { QPainter p(this); QColor color = currColor; @@ -131,15 +122,14 @@ void ColorValueBar::paintEvent(QPaintEvent* event) QRect barRect = rect(); barRect.setWidth(barRect.width() - triangleSize); - for (int y = barRect.y(); y <= barRect.bottom(); y++) { color.setHsvF(h, s, 1.0 - qreal(y) / height()); p.setPen(color); p.drawLine(barRect.x(), y, barRect.right(), y); } - QRectF triangleRect = QRectF(barRect.right(), v * height() - triangleSize / 2, - triangleSize, triangleSize); + QRectF triangleRect = + QRectF(barRect.right(), v * height() - triangleSize / 2, triangleSize, triangleSize); QPainterPath path; path.moveTo(triangleRect.left(), triangleRect.top() + triangleRect.height() / 2); @@ -163,50 +153,43 @@ QColor ColorValueBar::pointToColor(int x, int y) const return color; } -QPoint ColorValueBar::colorToPoint(const QColor& color) const +QPoint ColorValueBar::colorToPoint(const QColor &color) const { qreal h, s, v; color.getHsvF(&h, &s, &v); return QPoint(rect().x(), int((1.0 - v) * height())); } -ColorPicker::ColorPicker(QWidget* parent) : - ColorPickWidgetAbstract(parent), - ui(new Ui::ColorPicker), - pickingFromScreen(false) +ColorPicker::ColorPicker(QWidget *parent) + : ColorPickWidgetAbstract(parent), ui(new Ui::ColorPicker), pickingFromScreen(false) { ui->setupUi(this); - connect(ui->colorPickArea, &ColorPickArea::colorChanged, - this, &ColorPicker::setColor); - connect(ui->valuePickBar, &ColorValueBar::colorChanged, - this, &ColorPicker::setColor); - connect(ui->alphaChannelBar, &AlphaChannelBar::colorChanged, - this, [this](const QColor& color) { emit colorChanged(color); }); - connect(this, &ColorPicker::colorChanged, - ui->colorPickArea, &ColorPickArea::setColor); - connect(this, &ColorPicker::colorChanged, - ui->valuePickBar, &ColorValueBar::setColor); - connect(this, &ColorPicker::colorChanged, - ui->colorShow, &ColorShowWidget::setColor); - connect(this, &ColorPicker::colorChanged, - ui->alphaChannelBar, &AlphaChannelBar::setColor); + connect(ui->colorPickArea, &ColorPickArea::colorChanged, this, &ColorPicker::setColor); + connect(ui->valuePickBar, &ColorValueBar::colorChanged, this, &ColorPicker::setColor); + connect(ui->alphaChannelBar, &AlphaChannelBar::colorChanged, this, + [this](const QColor &color) { emit colorChanged(color); }); + connect(this, &ColorPicker::colorChanged, ui->colorPickArea, &ColorPickArea::setColor); + connect(this, &ColorPicker::colorChanged, ui->valuePickBar, &ColorValueBar::setColor); + connect(this, &ColorPicker::colorChanged, ui->colorShow, &ColorShowWidget::setColor); + connect(this, &ColorPicker::colorChanged, ui->alphaChannelBar, &AlphaChannelBar::setColor); - connect(ui->hueSpinBox, static_cast(&QSpinBox::valueChanged), - this, &ColorPicker::colorChannelChanged); - connect(ui->satSpinBox, static_cast(&QSpinBox::valueChanged), - this, &ColorPicker::colorChannelChanged); - connect(ui->valSpinBox, static_cast(&QSpinBox::valueChanged), - this, &ColorPicker::colorChannelChanged); - connect(ui->redSpinBox, static_cast(&QSpinBox::valueChanged), - this, &ColorPicker::colorChannelChanged); - connect(ui->blueSpinBox, static_cast(&QSpinBox::valueChanged), - this, &ColorPicker::colorChannelChanged); - connect(ui->greenSpinBox, static_cast(&QSpinBox::valueChanged), - this, &ColorPicker::colorChannelChanged); + connect(ui->hueSpinBox, static_cast(&QSpinBox::valueChanged), this, + &ColorPicker::colorChannelChanged); + connect(ui->satSpinBox, static_cast(&QSpinBox::valueChanged), this, + &ColorPicker::colorChannelChanged); + connect(ui->valSpinBox, static_cast(&QSpinBox::valueChanged), this, + &ColorPicker::colorChannelChanged); + connect(ui->redSpinBox, static_cast(&QSpinBox::valueChanged), this, + &ColorPicker::colorChannelChanged); + connect(ui->blueSpinBox, static_cast(&QSpinBox::valueChanged), this, + &ColorPicker::colorChannelChanged); + connect(ui->greenSpinBox, static_cast(&QSpinBox::valueChanged), this, + &ColorPicker::colorChannelChanged); connect(ui->hexLineEdit, &QLineEdit::textChanged, this, &ColorPicker::colorChannelChanged); - connect(ui->pickColorFromScreenButton, &QPushButton::clicked, this, &ColorPicker::startPickingFromScreen); + connect(ui->pickColorFromScreenButton, &QPushButton::clicked, this, + &ColorPicker::startPickingFromScreen); } ColorPicker::~ColorPicker() @@ -217,7 +200,7 @@ ColorPicker::~ColorPicker() } } -void ColorPicker::setColor(const QColor& color) +void ColorPicker::setColor(const QColor &color) { updateColor(color); emit colorChanged(currColor); @@ -255,7 +238,7 @@ void ColorPicker::colorChannelChanged() } } -void ColorPicker::updateColor(const QColor& color) +void ColorPicker::updateColor(const QColor &color) { QSignalBlocker s0(ui->redSpinBox); QSignalBlocker s1(ui->blueSpinBox); @@ -304,7 +287,7 @@ void ColorPicker::startPickingFromScreen() } } -void ColorPicker::mouseReleaseEvent(QMouseEvent* event) +void ColorPicker::mouseReleaseEvent(QMouseEvent *event) { if (pickingFromScreen) { setColor(getColorAtMouse()); @@ -315,7 +298,7 @@ void ColorPicker::mouseReleaseEvent(QMouseEvent* event) QWidget::mouseReleaseEvent(event); } -void ColorPicker::mouseMoveEvent(QMouseEvent* event) +void ColorPicker::mouseMoveEvent(QMouseEvent *event) { if (pickingFromScreen) { updateColor(getColorAtMouse()); @@ -326,9 +309,10 @@ void ColorPicker::mouseMoveEvent(QMouseEvent* event) QColor ColorPicker::getColorAtMouse() { const QDesktopWidget *desktop = QApplication::desktop(); - const QPixmap pixmap = QGuiApplication::screens().at(desktop->screenNumber()) - ->grabWindow(desktop->winId(), - QCursor::pos().x(), QCursor::pos().y(), 1, 1); + const QPixmap pixmap = + QGuiApplication::screens() + .at(desktop->screenNumber()) + ->grabWindow(desktop->winId(), QCursor::pos().x(), QCursor::pos().y(), 1, 1); return QColor(pixmap.toImage().pixel(0, 0)); } @@ -352,23 +336,24 @@ void ColorPicker::stopPickingFromScreen() } } -ColorShowWidget::ColorShowWidget(QWidget* parent) : ColorPickWidgetAbstract(parent) { } +ColorShowWidget::ColorShowWidget(QWidget *parent) : ColorPickWidgetAbstract(parent) {} -void ColorShowWidget::setColor(const QColor& c) +void ColorShowWidget::setColor(const QColor &c) { currColor = c; repaint(); } -void ColorShowWidget::paintEvent(QPaintEvent* event) +void ColorShowWidget::paintEvent(QPaintEvent *event) { QPainter p(this); const int miniRectWidth = rect().width() / 2; for (int y = rect().topLeft().ry(); y < rect().bottomRight().ry(); y++) { for (int x = rect().topLeft().rx(); x < rect().bottomRight().rx(); x++) { - p.setPen(((x % miniRectWidth) / (miniRectWidth / 2)) == ((y % miniRectWidth) / (miniRectWidth / 2)) - ? Qt::white - : Qt::black); + p.setPen(((x % miniRectWidth) / (miniRectWidth / 2)) + == ((y % miniRectWidth) / (miniRectWidth / 2)) + ? Qt::white + : Qt::black); p.drawPoint(x, y); } } @@ -378,7 +363,7 @@ void ColorShowWidget::paintEvent(QPaintEvent* event) p.end(); } -void AlphaChannelBar::setColor(const QColor& c) +void AlphaChannelBar::setColor(const QColor &c) { if (c == currColor) { return; @@ -388,7 +373,7 @@ void AlphaChannelBar::setColor(const QColor& c) emit colorChanged(currColor); } -void AlphaChannelBar::paintEvent(QPaintEvent* event) +void AlphaChannelBar::paintEvent(QPaintEvent *event) { QPainter p(this); QRect barRect = rect(); @@ -403,17 +388,18 @@ void AlphaChannelBar::paintEvent(QPaintEvent* event) const int miniRectWidth = barRect.width() / 2; for (int y = barRect.topLeft().ry(); y < barRect.bottomRight().ry(); y++) { for (int x = barRect.topLeft().rx(); x < barRect.bottomRight().rx(); x++) { - p.setPen(((x % miniRectWidth) / (miniRectWidth / 2)) == ((y % miniRectWidth) / (miniRectWidth / 2)) - ? Qt::white - : Qt::black); + p.setPen(((x % miniRectWidth) / (miniRectWidth / 2)) + == ((y % miniRectWidth) / (miniRectWidth / 2)) + ? Qt::white + : Qt::black); p.drawPoint(x, y); p.setPen(pointToColor(x, y)); p.drawPoint(x, y); } } - QRectF triangleRect = QRectF(barRect.right(), a * height() - triangleSize / 2, - triangleSize, triangleSize); + QRectF triangleRect = + QRectF(barRect.right(), a * height() - triangleSize / 2, triangleSize, triangleSize); QPainterPath path; path.moveTo(triangleRect.left(), triangleRect.top() + triangleRect.height() / 2); diff --git a/src/widgets/ColorPicker.h b/src/widgets/ColorPicker.h index e9883dfc..8c45ec7c 100644 --- a/src/widgets/ColorPicker.h +++ b/src/widgets/ColorPicker.h @@ -12,14 +12,14 @@ class ColorPickWidgetAbstract : public QWidget { Q_OBJECT public: - ColorPickWidgetAbstract(QWidget *parent = nullptr): QWidget(parent) {} + ColorPickWidgetAbstract(QWidget *parent = nullptr) : QWidget(parent) {} virtual ~ColorPickWidgetAbstract() {} signals: - void colorChanged(const QColor& color); + void colorChanged(const QColor &color); public slots: - virtual void setColor(const QColor& color) = 0; + virtual void setColor(const QColor &color) = 0; protected: QColor currColor; @@ -48,7 +48,6 @@ public: void setAlphaEnabled(bool enabled); - public slots: /** * @brief setColor sets displayed color to @a color and emits colorChanged signal. @@ -60,7 +59,7 @@ public slots: /** * @brief updateColor sets displayed color to @a color. */ - void updateColor(const QColor& color); + void updateColor(const QColor &color); /** * @brief startPickingFromScreen starts process of picking from screen. @@ -74,8 +73,8 @@ public slots: void stopPickingFromScreen(); protected: - void mouseReleaseEvent(QMouseEvent* event) override; - void mouseMoveEvent(QMouseEvent* event) override; + void mouseReleaseEvent(QMouseEvent *event) override; + void mouseMoveEvent(QMouseEvent *event) override; private: Ui::ColorPicker *ui; @@ -93,17 +92,18 @@ namespace ColorPickerHelpers { /** * @brief The ColorPickerWidget class is parent class for ColorPickArea and ColorValueBar classes. */ -class ColorPickerWidget : public ColorPickWidgetAbstract { +class ColorPickerWidget : public ColorPickWidgetAbstract +{ Q_OBJECT public: ColorPickerWidget(QWidget *parent = nullptr); protected: - void mouseReleaseEvent(QMouseEvent* event) override; - void mousePressEvent(QMouseEvent* event) override; - void mouseMoveEvent(QMouseEvent* event) override; + void mouseReleaseEvent(QMouseEvent *event) override; + void mousePressEvent(QMouseEvent *event) override; + void mouseMoveEvent(QMouseEvent *event) override; - virtual void mouseEvent(QMouseEvent* event); + virtual void mouseEvent(QMouseEvent *event); /** * @brief pointToColor converts coordinates on widget to color these coordinates represents. @@ -113,7 +113,7 @@ protected: /** * @brief colorToPoint converts color to coordinates that represent this color. */ - virtual QPoint colorToPoint(const QColor& color) const = 0; + virtual QPoint colorToPoint(const QColor &color) const = 0; }; class ColorShowWidget : public ColorPickWidgetAbstract @@ -122,7 +122,7 @@ class ColorShowWidget : public ColorPickWidgetAbstract public: explicit ColorShowWidget(QWidget *parent = nullptr); - void setColor(const QColor& c) override; + void setColor(const QColor &c) override; protected: void paintEvent(QPaintEvent *event) override; @@ -138,7 +138,7 @@ class ColorPickArea : public ColorPickerWidget public: explicit ColorPickArea(QWidget *parent = nullptr); - void setColor(const QColor& c) override; + void setColor(const QColor &c) override; protected: void paintEvent(QPaintEvent *event) override; @@ -146,7 +146,7 @@ protected: private: QColor pointToColor(int x, int y) const override; - QPoint colorToPoint(const QColor& color) const override; + QPoint colorToPoint(const QColor &color) const override; }; class AlphaChannelBar : public ColorPickerWidget @@ -155,7 +155,7 @@ class AlphaChannelBar : public ColorPickerWidget public: AlphaChannelBar(QWidget *parent = nullptr) : ColorPickerWidget(parent) {} - void setColor(const QColor& c) override; + void setColor(const QColor &c) override; protected: void paintEvent(QPaintEvent *event) override; @@ -163,7 +163,7 @@ protected: private: QColor pointToColor(int x, int y) const override; - QPoint colorToPoint(const QColor& color) const override; + QPoint colorToPoint(const QColor &color) const override; }; /** @@ -176,7 +176,7 @@ class ColorValueBar : public ColorPickerWidget public: ColorValueBar(QWidget *parent = nullptr) : ColorPickerWidget(parent) {} - void setColor(const QColor& c) override; + void setColor(const QColor &c) override; protected: void paintEvent(QPaintEvent *event) override; @@ -184,7 +184,7 @@ protected: private: QColor pointToColor(int x, int y) const override; - QPoint colorToPoint(const QColor& color) const override; + QPoint colorToPoint(const QColor &color) const override; }; } diff --git a/src/widgets/ColorThemeComboBox.cpp b/src/widgets/ColorThemeComboBox.cpp index de2dfa03..d9383a33 100644 --- a/src/widgets/ColorThemeComboBox.cpp +++ b/src/widgets/ColorThemeComboBox.cpp @@ -7,8 +7,8 @@ ColorThemeComboBox::ColorThemeComboBox(QWidget *parent) : QComboBox(parent), showOnlyCustom(false) { - connect(this, static_cast(&QComboBox::currentIndexChanged), - this, &ColorThemeComboBox::onCurrentIndexChanged); + connect(this, static_cast(&QComboBox::currentIndexChanged), this, + &ColorThemeComboBox::onCurrentIndexChanged); updateFromConfig(); } @@ -17,22 +17,21 @@ void ColorThemeComboBox::updateFromConfig(bool interfaceThemeChanged) QSignalBlocker signalBlockerColorBox(this); const int curInterfaceThemeIndex = Config()->getInterfaceTheme(); - const QList themes(showOnlyCustom - ? ThemeWorker().customThemes() - : Core()->getColorThemes()); + const QList themes(showOnlyCustom ? ThemeWorker().customThemes() + : Core()->getColorThemes()); clear(); for (const QString &theme : themes) { - if (ThemeWorker().isCustomTheme(theme) || - (Configuration::cutterInterfaceThemesList()[curInterfaceThemeIndex].flag & - Configuration::relevantThemes[theme])) { + if (ThemeWorker().isCustomTheme(theme) + || (Configuration::cutterInterfaceThemesList()[curInterfaceThemeIndex].flag + & Configuration::relevantThemes[theme])) { addItem(theme); } } - QString curTheme = interfaceThemeChanged - ? Config()->getLastThemeOf(Configuration::cutterInterfaceThemesList()[curInterfaceThemeIndex]) - : Config()->getColorTheme(); + QString curTheme = interfaceThemeChanged ? Config()->getLastThemeOf( + Configuration::cutterInterfaceThemesList()[curInterfaceThemeIndex]) + : Config()->getColorTheme(); const int index = findText(curTheme); setCurrentIndex(index == -1 ? 0 : index); diff --git a/src/widgets/ColorThemeComboBox.h b/src/widgets/ColorThemeComboBox.h index 01b10ff7..50fb74b5 100644 --- a/src/widgets/ColorThemeComboBox.h +++ b/src/widgets/ColorThemeComboBox.h @@ -20,11 +20,12 @@ public: public slots: /** - * @brief updateFromConfig updates list of themes to be shown. - * @param interfaceThemeChanged should be set to true if the interface theme of Cutter was changed - * since the last call to the function. This will preserve the selected item in the combo box. - * - */ + * @brief updateFromConfig updates list of themes to be shown. + * @param interfaceThemeChanged should be set to true if the interface theme of Cutter was + * changed since the last call to the function. This will preserve the selected item in the + * combo box. + * + */ void updateFromConfig(bool interfaceThemeChanged = false); private slots: diff --git a/src/widgets/ColorThemeListView.cpp b/src/widgets/ColorThemeListView.cpp index 499c6e0e..7b37392f 100644 --- a/src/widgets/ColorThemeListView.cpp +++ b/src/widgets/ColorThemeListView.cpp @@ -21,24 +21,24 @@ constexpr int allFieldsRole = Qt::UserRole + 2; -struct OptionInfo { +struct OptionInfo +{ QString info; QString displayingtext; }; extern const QMap optionInfoMap__; -ColorOptionDelegate::ColorOptionDelegate(QObject* parent) : QStyledItemDelegate (parent) +ColorOptionDelegate::ColorOptionDelegate(QObject *parent) : QStyledItemDelegate(parent) { resetButtonPixmap = getPixmapFromSvg(":/img/icons/reset.svg", qApp->palette().text().color()); - connect(qApp, &QGuiApplication::paletteChanged, this, - [this](){ - resetButtonPixmap = getPixmapFromSvg(":/img/icons/reset.svg", qApp->palette().text().color()); + connect(qApp, &QGuiApplication::paletteChanged, this, [this]() { + resetButtonPixmap = + getPixmapFromSvg(":/img/icons/reset.svg", qApp->palette().text().color()); }); } -void ColorOptionDelegate::paint(QPainter *painter, - const QStyleOptionViewItem &option, +void ColorOptionDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { int margin = this->margin; @@ -68,7 +68,8 @@ void ColorOptionDelegate::paint(QPainter *painter, colorRect.setWidth(colorRect.height()); QRect descTextRect; - descTextRect.setTopLeft(colorRect.topRight() + QPoint(margin, colorRect.height() / 2 - fontHeight / 2)); + descTextRect.setTopLeft(colorRect.topRight() + + QPoint(margin, colorRect.height() / 2 - fontHeight / 2)); descTextRect.setWidth(optionRect.width() - (descTextRect.left() - optionRect.left()) - margin); descTextRect.setHeight(fontHeight); @@ -115,19 +116,19 @@ void ColorOptionDelegate::paint(QPainter *painter, if (paintResetButton) { painter->drawPixmap(resetButtonRect, resetButtonPixmap); - auto self = const_cast(this); + auto self = const_cast(this); self->resetButtonRect = resetButtonRect; } if (option.rect.contains(this->resetButtonRect) && this->resetButtonRect != resetButtonRect) { - auto self = const_cast(this); - self->resetButtonRect = QRect(0,0,0,0); + auto self = const_cast(this); + self->resetButtonRect = QRect(0, 0, 0, 0); } painter->setPen(qApp->palette().text().color()); - QString name = painter->fontMetrics().elidedText( - optionInfoMap__[currCO.optionName].displayingtext, - Qt::ElideRight, optionNameRect.width()); + QString name = + painter->fontMetrics().elidedText(optionInfoMap__[currCO.optionName].displayingtext, + Qt::ElideRight, optionNameRect.width()); painter->drawText(optionNameRect, name); QPainterPath roundedOptionRect; @@ -155,9 +156,8 @@ void ColorOptionDelegate::paint(QPainter *painter, painter->fillPath(roundedColorRect, currCO.color); QString desc = painter->fontMetrics().elidedText( - currCO.optionName + ": " + - optionInfoMap__[currCO.optionName].info, Qt::ElideRight, - descTextRect.width()); + currCO.optionName + ": " + optionInfoMap__[currCO.optionName].info, Qt::ElideRight, + descTextRect.width()); painter->setPen(qApp->palette().text().color()); painter->setBrush(qApp->palette().text()); painter->drawText(descTextRect, desc); @@ -165,7 +165,8 @@ void ColorOptionDelegate::paint(QPainter *painter, painter->restore(); } -QSize ColorOptionDelegate::sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const +QSize ColorOptionDelegate::sizeHint(const QStyleOptionViewItem &option, + const QModelIndex &index) const { qreal margin = this->margin; qreal fontHeight = option.fontMetrics.height(); @@ -186,7 +187,7 @@ QRect ColorOptionDelegate::getResetButtonRect() const return resetButtonRect; } -QPixmap ColorOptionDelegate::getPixmapFromSvg(const QString& fileName, const QColor& after) const +QPixmap ColorOptionDelegate::getPixmapFromSvg(const QString &fileName, const QColor &after) const { QFile file(fileName); if (!file.open(QIODevice::ReadOnly)) { @@ -205,11 +206,10 @@ QPixmap ColorOptionDelegate::getPixmapFromSvg(const QString& fileName, const QCo return pix; } -ColorThemeListView::ColorThemeListView(QWidget *parent) : - QListView (parent) +ColorThemeListView::ColorThemeListView(QWidget *parent) : QListView(parent) { - QSortFilterProxyModel* proxy = new QSortFilterProxyModel(this); - ColorSettingsModel* model = new ColorSettingsModel(this); + QSortFilterProxyModel *proxy = new QSortFilterProxyModel(this); + ColorSettingsModel *model = new ColorSettingsModel(this); proxy->setSourceModel(model); model->updateTheme(); setModel(proxy); @@ -220,8 +220,8 @@ ColorThemeListView::ColorThemeListView(QWidget *parent) : setItemDelegate(new ColorOptionDelegate(this)); setResizeMode(ResizeMode::Adjust); - QJsonArray rgb = colorSettingsModel()->getTheme() - .object().find("gui.background").value().toArray(); + QJsonArray rgb = + colorSettingsModel()->getTheme().object().find("gui.background").value().toArray(); if (rgb.size() == 3) { backgroundColor = QColor(rgb[0].toInt(), rgb[1].toInt(), rgb[2].toInt()); } else { @@ -236,8 +236,7 @@ ColorThemeListView::ColorThemeListView(QWidget *parent) : setMouseTracking(true); } -void ColorThemeListView::currentChanged(const QModelIndex ¤t, - const QModelIndex &previous) +void ColorThemeListView::currentChanged(const QModelIndex ¤t, const QModelIndex &previous) { ColorOption prev = previous.data(Qt::UserRole).value(); Config()->setColor(prev.optionName, prev.color); @@ -249,8 +248,8 @@ void ColorThemeListView::currentChanged(const QModelIndex ¤t, emit itemChanged(current.data(Qt::UserRole).value().color); } -void ColorThemeListView::dataChanged(const QModelIndex& topLeft, const QModelIndex& bottomRight, - const QVector& roles) +void ColorThemeListView::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight, + const QVector &roles) { ColorOption curr = topLeft.data(Qt::UserRole).value(); if (curr.optionName == "gui.background") { @@ -261,13 +260,15 @@ void ColorThemeListView::dataChanged(const QModelIndex& topLeft, const QModelInd emit dataChanged(curr); } -void ColorThemeListView::mouseReleaseEvent(QMouseEvent* e) +void ColorThemeListView::mouseReleaseEvent(QMouseEvent *e) { - if (qobject_cast(itemDelegate())->getResetButtonRect().contains(e->pos())) { + if (qobject_cast(itemDelegate()) + ->getResetButtonRect() + .contains(e->pos())) { ColorOption co = currentIndex().data(Qt::UserRole).value(); co.changed = false; - QJsonArray rgb = ThemeWorker().getTheme( - Config()->getColorTheme()).object()[co.optionName].toArray(); + QJsonArray rgb = + ThemeWorker().getTheme(Config()->getColorTheme()).object()[co.optionName].toArray(); co.color = QColor(rgb[0].toInt(), rgb[1].toInt(), rgb[2].toInt()); model()->setData(currentIndex(), QVariant::fromValue(co)); QCursor c; @@ -276,9 +277,11 @@ void ColorThemeListView::mouseReleaseEvent(QMouseEvent* e) } } -void ColorThemeListView::mouseMoveEvent(QMouseEvent* e) +void ColorThemeListView::mouseMoveEvent(QMouseEvent *e) { - if (qobject_cast(itemDelegate())->getResetButtonRect().contains(e->pos())) { + if (qobject_cast(itemDelegate()) + ->getResetButtonRect() + .contains(e->pos())) { QCursor c; c.setShape(Qt::CursorShape::PointingHandCursor); setCursor(c); @@ -289,9 +292,10 @@ void ColorThemeListView::mouseMoveEvent(QMouseEvent* e) } } -ColorSettingsModel* ColorThemeListView::colorSettingsModel() const +ColorSettingsModel *ColorThemeListView::colorSettingsModel() const { - return static_cast(static_cast(model())->sourceModel()); + return static_cast( + static_cast(model())->sourceModel()); } void ColorThemeListView::blinkTimeout() @@ -319,20 +323,21 @@ void ColorThemeListView::blinkTimeout() emit blink(); } -ColorSettingsModel::ColorSettingsModel(QObject *parent) : QAbstractListModel (parent) { } +ColorSettingsModel::ColorSettingsModel(QObject *parent) : QAbstractListModel(parent) {} QVariant ColorSettingsModel::data(const QModelIndex &index, int role) const { if (!index.isValid()) { - return QVariant(); + return QVariant(); } if (index.row() < 0 || index.row() >= theme.size()) { - return QVariant(); + return QVariant(); } if (role == Qt::DisplayRole) { - return QVariant::fromValue(optionInfoMap__[theme.at(index.row()).optionName].displayingtext); + return QVariant::fromValue( + optionInfoMap__[theme.at(index.row()).optionName].displayingtext); } if (role == Qt::UserRole) { @@ -345,16 +350,15 @@ QVariant ColorSettingsModel::data(const QModelIndex &index, int role) const if (role == allFieldsRole) { const QString name = theme.at(index.row()).optionName; - return QVariant::fromValue(optionInfoMap__[name].displayingtext + " " + - optionInfoMap__[theme.at(index.row()).optionName].info + " " + - name); + return QVariant::fromValue(optionInfoMap__[name].displayingtext + " " + + optionInfoMap__[theme.at(index.row()).optionName].info + " " + + name); } - return QVariant(); } -bool ColorSettingsModel::setData(const QModelIndex& index, const QVariant& value, int role) +bool ColorSettingsModel::setData(const QModelIndex &index, const QVariant &value, int role) { if (!index.isValid() || role != Qt::EditRole) { return false; @@ -376,10 +380,12 @@ void ColorSettingsModel::updateTheme() if (rgb.size() != 4) { continue; } - theme.push_back({it.key(), QColor(rgb[0].toInt(), rgb[1].toInt(), rgb[2].toInt(), rgb[3].toInt()), false}); + theme.push_back({ it.key(), + QColor(rgb[0].toInt(), rgb[1].toInt(), rgb[2].toInt(), rgb[3].toInt()), + false }); } - std::sort(theme.begin(), theme.end(), [](const ColorOption& f, const ColorOption& s) { + std::sort(theme.begin(), theme.end(), [](const ColorOption &f, const ColorOption &s) { QString s1 = optionInfoMap__[f.optionName].displayingtext; QString s2 = optionInfoMap__[s.optionName].displayingtext; int r = s1.compare(s2, Qt::CaseSensitivity::CaseInsensitive); @@ -396,491 +402,127 @@ QJsonDocument ColorSettingsModel::getTheme() const int r, g, b, a; for (auto &it : theme) { it.color.getRgb(&r, &g, &b, &a); - obj.insert(it.optionName, QJsonArray({r, g, b, a})); + obj.insert(it.optionName, QJsonArray({ r, g, b, a })); } return QJsonDocument(obj); } const QMap optionInfoMap__ = { -{ - "comment", { - QObject::tr("Color of comment generated by Rizin"), - QObject::tr("Comment") - } -}, -{ - "usrcmt", { - QObject::tr("Comment created by user"), - QObject::tr("Color of user Comment") - } -}, -{ - "args", { - "", - "args" - } -}, -{ - "fname", { - QObject::tr("Color of names of functions"), - QObject::tr("Function name") - } -}, -{ - "floc", { - QObject::tr("Color of function location"), - QObject::tr("Function location") - } -}, -{ - "fline", { - QObject::tr("Color of ascii line in left side that shows what opcodes are belong to function"), - QObject::tr("Function line") - } -}, -{ - "flag", { - QObject::tr("Color of flags (similar to bookmarks for offset)"), - QObject::tr("Flag") - } -}, -{ - "label", { - "", - QObject::tr("Label") - } -}, -{ - "help", { - "", - QObject::tr("Help") - } -}, -{ - "flow", { - QObject::tr("Color of lines showing jump destination"), - QObject::tr("Flow") - } -}, -{ - "flow2", { - "", - QObject::tr("flow2") - } -}, -{ - "prompt", { - QObject::tr("Info"), - QObject::tr("prompt") - } -}, -{ - "offset", { - QObject::tr("Color of offsets"), - QObject::tr("Offset") - } -}, -{ - "input", { - QObject::tr("Info"), - QObject::tr("input") - } -}, -{ - "invalid", { - QObject::tr("Invalid opcode color"), - QObject::tr("invalid") - } -}, -{ - "other", { - "", - QObject::tr("other") - } -}, -{ - "b0x00", { - QObject::tr("0x00 opcode color"), - "b0x00" - } -}, -{ - "b0x7f", { - QObject::tr("0x7f opcode color"), - "b0x7f" - } -}, -{ - "b0xff", { - QObject::tr("0xff opcode color"), - "b0xff" - } -}, -{ - "math", { - QObject::tr("Color of arithmetic opcodes (add, div, mul etc)"), - QObject::tr("Arithmetic") - } -}, -{ - "bin", { - QObject::tr("Color of binary operations (and, or, xor etc)."), - QObject::tr("Binary") - } -}, -{ - "btext", { - QObject::tr("Color of object names, commas between operators, squared brackets and operators " - "inside them."), - QObject::tr("Text") - } -}, -{ - "push", { - QObject::tr("push opcode color"), - "push" - } -}, -{ - "pop", { - QObject::tr("pop opcode color"), - "pop" - } -}, -{ - "crypto", { - QObject::tr("Cryptographic color"), - "crypto" - } -}, -{ - "jmp", { - QObject::tr("jmp instructions color"), - "jmp" - } -}, -{ - "cjmp", { - QObject::tr("Color of conditional jump opcodes such as je, jg, jne etc"), - QObject::tr("Conditional jump") - } -}, -{ - "call", { - QObject::tr("call instructions color (ccall, rcall, call etc)"), - "call" - } -}, -{ - "nop", { - QObject::tr("nop opcode color"), - "nop" - } -}, -{ - "ret", { - QObject::tr("ret opcode color"), - "ret" - } -}, -{ - "trap", { - QObject::tr("Color of interrupts"), - QObject::tr("Interrupts") - } -}, -{ - "swi", { - QObject::tr("swi opcode color"), - "swi" - } -}, -{ - "cmp", { - QObject::tr("Color of compare instructions such as test and cmp"), - QObject::tr("Compare instructions") - } -}, -{ - "reg", { - QObject::tr("Registers color"), - QObject::tr("Register") - } -}, -{ - "creg", { - "", - "creg" - } -}, -{ - "num", { - QObject::tr("Color of numeric constants and object pointers"), - QObject::tr("Constants") - } -}, -{ - "mov", { - QObject::tr("Color of move instructions such as mov, movd, lea etc"), - QObject::tr("Move instructions") - } -}, -{ - "func_var", { - QObject::tr("Function variable color"), - QObject::tr("Function variable") - } -}, -{ - "func_var_type", { - QObject::tr("Function variable (local or argument) type color"), - QObject::tr("Variable type") - } -}, -{ - "func_var_addr", { - QObject::tr("Function variable address color"), - QObject::tr("Variable address") - } -}, -{ - "widget_bg", { - "", - "widget_bg" - } -}, -{ - "widget_sel", { - "", - "widget_sel" - } -}, -{ - "ai.read", { - "", - "ai.read" - } -}, -{ - "ai.write", { - "", - "ai.write" - } -}, -{ - "ai.exec", { - "", - "ai.exec" - } -}, -{ - "ai.seq", { - "", - "ai.seq" - } -}, -{ - "ai.ascii", { - "", - "ai.ascii" - } -}, -{ - "graph.box", { - "", - "graph.box" - } -}, -{ - "graph.box2", { - "", - "graph.box2" - } -}, -{ - "graph.box3", { - "", - "graph.box3" - } -}, -{ - "graph.box4", { - "", - "graph.box4" - } -}, -{ - "graph.true", { - QObject::tr("In graph view jump arrow true"), - QObject::tr("Arrow true") - } -}, -{ - "graph.false", { - QObject::tr("In graph view jump arrow false"), - QObject::tr("Arrow false") - } -}, -{ - "graph.trufae", { - QObject::tr("In graph view jump arrow (no condition)"), - QObject::tr("Arrow") - } -}, -{ - "graph.current", { - "", - "graph.current" - } -}, -{ - "graph.traced", { - "", - "graph.traced" - } -}, -{ - "gui.overview.node", { - QObject::tr("Background color of Graph Overview's node"), - QObject::tr("Graph Overview node") - } -}, -{ - "gui.overview.fill", { - QObject::tr("Fill color of Graph Overview's selection"), - QObject::tr("Graph Overview fill") - } -}, -{ - "gui.overview.border", { - QObject::tr("Border color of Graph Overview's selection"), - QObject::tr("Graph Overview border") - } -}, -{ - "gui.cflow", { - "", - "gui.cflow" - } -}, -{ - "gui.dataoffset", { - "", - "gui.dataoffset" - } -}, -{ - "gui.background", { - QObject::tr("General background color"), - QObject::tr("Background") - } -}, -{ - "gui.alt_background", { - QObject::tr("Background color of non-focused graph node"), - QObject::tr("Node background") - } -}, -{ - "gui.disass_selected", { - QObject::tr("Background of current graph node"), - QObject::tr("Current graph node") - } -}, -{ - "gui.border", { - QObject::tr("Color of node border in graph view"), - QObject::tr("Node border") - } -}, -{ - "lineHighlight", { - QObject::tr("Selected line background color"), - QObject::tr("Line highlight") - } -}, -{ - "wordHighlight", { - QObject::tr("Background color of selected word"), - QObject::tr("Word higlight") - } -}, -{ - "gui.main", { - QObject::tr("Main function color"), - QObject::tr("Main") - } -}, -{ - "gui.imports", { - "", - "gui.imports" - } -}, -{ - "highlightPC", { - "", - "highlightPC" - } -}, -{ - "gui.navbar.err", { - "", - "gui.navbar.err" - } -}, -{ - "gui.navbar.seek", { - "", - "gui.navbar.seek" - } -}, -{ - "angui.navbar.str", { - "", - "angui.navbar.str" - } -}, -{ - "gui.navbar.pc", { - "", - "gui.navbar.pc" - } -}, -{ - "gui.navbar.sym", { - "", - "gui.navbar.sym" - } -}, -{ - "gui.navbar.code", { - QObject::tr("Code section color in navigation bar"), - QObject::tr("Navbar code") - } -}, -{ - "gui.navbar.empty", { - QObject::tr("Empty section color in navigation bar"), - QObject::tr("Navbar empty") - } -}, -{ - "ucall", { - "", - QObject::tr("ucall") - } -}, -{ - "ujmp", { - "", - QObject::tr("ujmp") - } -}, -{ - "gui.breakpoint_background", { - "", - QObject::tr("Breakpoint background") - } -} + { "comment", { QObject::tr("Color of comment generated by Rizin"), QObject::tr("Comment") } }, + { "usrcmt", { QObject::tr("Comment created by user"), QObject::tr("Color of user Comment") } }, + { "args", { "", "args" } }, + { "fname", { QObject::tr("Color of names of functions"), QObject::tr("Function name") } }, + { "floc", { QObject::tr("Color of function location"), QObject::tr("Function location") } }, + { "fline", + { QObject::tr( + "Color of ascii line in left side that shows what opcodes are belong to function"), + QObject::tr("Function line") } }, + { "flag", + { QObject::tr("Color of flags (similar to bookmarks for offset)"), QObject::tr("Flag") } }, + { "label", { "", QObject::tr("Label") } }, + { "help", { "", QObject::tr("Help") } }, + { "flow", { QObject::tr("Color of lines showing jump destination"), QObject::tr("Flow") } }, + { "flow2", { "", QObject::tr("flow2") } }, + { "prompt", { QObject::tr("Info"), QObject::tr("prompt") } }, + { "offset", { QObject::tr("Color of offsets"), QObject::tr("Offset") } }, + { "input", { QObject::tr("Info"), QObject::tr("input") } }, + { "invalid", { QObject::tr("Invalid opcode color"), QObject::tr("invalid") } }, + { "other", { "", QObject::tr("other") } }, + { "b0x00", { QObject::tr("0x00 opcode color"), "b0x00" } }, + { "b0x7f", { QObject::tr("0x7f opcode color"), "b0x7f" } }, + { "b0xff", { QObject::tr("0xff opcode color"), "b0xff" } }, + { "math", + { QObject::tr("Color of arithmetic opcodes (add, div, mul etc)"), + QObject::tr("Arithmetic") } }, + { "bin", + { QObject::tr("Color of binary operations (and, or, xor etc)."), QObject::tr("Binary") } }, + { "btext", + { QObject::tr( + "Color of object names, commas between operators, squared brackets and operators " + "inside them."), + QObject::tr("Text") } }, + { "push", { QObject::tr("push opcode color"), "push" } }, + { "pop", { QObject::tr("pop opcode color"), "pop" } }, + { "crypto", { QObject::tr("Cryptographic color"), "crypto" } }, + { "jmp", { QObject::tr("jmp instructions color"), "jmp" } }, + { "cjmp", + { QObject::tr("Color of conditional jump opcodes such as je, jg, jne etc"), + QObject::tr("Conditional jump") } }, + { "call", { QObject::tr("call instructions color (ccall, rcall, call etc)"), "call" } }, + { "nop", { QObject::tr("nop opcode color"), "nop" } }, + { "ret", { QObject::tr("ret opcode color"), "ret" } }, + { "trap", { QObject::tr("Color of interrupts"), QObject::tr("Interrupts") } }, + { "swi", { QObject::tr("swi opcode color"), "swi" } }, + { "cmp", + { QObject::tr("Color of compare instructions such as test and cmp"), + QObject::tr("Compare instructions") } }, + { "reg", { QObject::tr("Registers color"), QObject::tr("Register") } }, + { "creg", { "", "creg" } }, + { "num", + { QObject::tr("Color of numeric constants and object pointers"), QObject::tr("Constants") } }, + { "mov", + { QObject::tr("Color of move instructions such as mov, movd, lea etc"), + QObject::tr("Move instructions") } }, + { "func_var", { QObject::tr("Function variable color"), QObject::tr("Function variable") } }, + { "func_var_type", + { QObject::tr("Function variable (local or argument) type color"), + QObject::tr("Variable type") } }, + { "func_var_addr", + { QObject::tr("Function variable address color"), QObject::tr("Variable address") } }, + { "widget_bg", { "", "widget_bg" } }, + { "widget_sel", { "", "widget_sel" } }, + { "ai.read", { "", "ai.read" } }, + { "ai.write", { "", "ai.write" } }, + { "ai.exec", { "", "ai.exec" } }, + { "ai.seq", { "", "ai.seq" } }, + { "ai.ascii", { "", "ai.ascii" } }, + { "graph.box", { "", "graph.box" } }, + { "graph.box2", { "", "graph.box2" } }, + { "graph.box3", { "", "graph.box3" } }, + { "graph.box4", { "", "graph.box4" } }, + { "graph.true", { QObject::tr("In graph view jump arrow true"), QObject::tr("Arrow true") } }, + { "graph.false", + { QObject::tr("In graph view jump arrow false"), QObject::tr("Arrow false") } }, + { "graph.trufae", + { QObject::tr("In graph view jump arrow (no condition)"), QObject::tr("Arrow") } }, + { "graph.current", { "", "graph.current" } }, + { "graph.traced", { "", "graph.traced" } }, + { "gui.overview.node", + { QObject::tr("Background color of Graph Overview's node"), + QObject::tr("Graph Overview node") } }, + { "gui.overview.fill", + { QObject::tr("Fill color of Graph Overview's selection"), + QObject::tr("Graph Overview fill") } }, + { "gui.overview.border", + { QObject::tr("Border color of Graph Overview's selection"), + QObject::tr("Graph Overview border") } }, + { "gui.cflow", { "", "gui.cflow" } }, + { "gui.dataoffset", { "", "gui.dataoffset" } }, + { "gui.background", { QObject::tr("General background color"), QObject::tr("Background") } }, + { "gui.alt_background", + { QObject::tr("Background color of non-focused graph node"), + QObject::tr("Node background") } }, + { "gui.disass_selected", + { QObject::tr("Background of current graph node"), QObject::tr("Current graph node") } }, + { "gui.border", + { QObject::tr("Color of node border in graph view"), QObject::tr("Node border") } }, + { "lineHighlight", + { QObject::tr("Selected line background color"), QObject::tr("Line highlight") } }, + { "wordHighlight", + { QObject::tr("Background color of selected word"), QObject::tr("Word higlight") } }, + { "gui.main", { QObject::tr("Main function color"), QObject::tr("Main") } }, + { "gui.imports", { "", "gui.imports" } }, + { "highlightPC", { "", "highlightPC" } }, + { "gui.navbar.err", { "", "gui.navbar.err" } }, + { "gui.navbar.seek", { "", "gui.navbar.seek" } }, + { "angui.navbar.str", { "", "angui.navbar.str" } }, + { "gui.navbar.pc", { "", "gui.navbar.pc" } }, + { "gui.navbar.sym", { "", "gui.navbar.sym" } }, + { "gui.navbar.code", + { QObject::tr("Code section color in navigation bar"), QObject::tr("Navbar code") } }, + { "gui.navbar.empty", + { QObject::tr("Empty section color in navigation bar"), QObject::tr("Navbar empty") } }, + { "ucall", { "", QObject::tr("ucall") } }, + { "ujmp", { "", QObject::tr("ujmp") } }, + { "gui.breakpoint_background", { "", QObject::tr("Breakpoint background") } } }; diff --git a/src/widgets/ColorThemeListView.h b/src/widgets/ColorThemeListView.h index 4feb004d..a1eb5103 100644 --- a/src/widgets/ColorThemeListView.h +++ b/src/widgets/ColorThemeListView.h @@ -7,7 +7,8 @@ #include #include -struct ColorOption { +struct ColorOption +{ QString optionName; QColor color; bool changed; @@ -23,20 +24,18 @@ public: ColorThemeListView(QWidget *parent = nullptr); virtual ~ColorThemeListView() override {} - ColorSettingsModel* colorSettingsModel() const; + ColorSettingsModel *colorSettingsModel() const; protected slots: - void currentChanged(const QModelIndex ¤t, - const QModelIndex &previous) override; + void currentChanged(const QModelIndex ¤t, const QModelIndex &previous) override; - void dataChanged(const QModelIndex & topLeft, const QModelIndex & bottomRight, + void dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight, const QVector &roles = QVector()) override; void mouseReleaseEvent(QMouseEvent *e) override; void mouseMoveEvent(QMouseEvent *e) override; - private slots: void blinkTimeout(); @@ -86,8 +85,7 @@ public: ColorOptionDelegate(QObject *parent = nullptr); ~ColorOptionDelegate() override {} - void paint(QPainter *painter, - const QStyleOptionViewItem &option, + void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override; QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const override; @@ -99,7 +97,7 @@ private: QPixmap resetButtonPixmap; QRect resetButtonRect; - QPixmap getPixmapFromSvg(const QString& fileName, const QColor& after) const; + QPixmap getPixmapFromSvg(const QString &fileName, const QColor &after) const; }; #endif // COLORTHEMELISTVIEW_H diff --git a/src/widgets/ComboQuickFilterView.cpp b/src/widgets/ComboQuickFilterView.cpp index 1a96f260..0f9d827c 100644 --- a/src/widgets/ComboQuickFilterView.cpp +++ b/src/widgets/ComboQuickFilterView.cpp @@ -1,15 +1,13 @@ #include "ComboQuickFilterView.h" #include "ui_ComboQuickFilterView.h" -ComboQuickFilterView::ComboQuickFilterView(QWidget *parent) : - QWidget(parent), - ui(new Ui::ComboQuickFilterView) +ComboQuickFilterView::ComboQuickFilterView(QWidget *parent) + : QWidget(parent), ui(new Ui::ComboQuickFilterView) { ui->setupUi(this); - connect(ui->lineEdit, &QLineEdit::textChanged, this, [this](const QString & text) { - emit filterTextChanged(text); - }); + connect(ui->lineEdit, &QLineEdit::textChanged, this, + [this](const QString &text) { emit filterTextChanged(text); }); } ComboQuickFilterView::~ComboQuickFilterView() diff --git a/src/widgets/CommentsWidget.cpp b/src/widgets/CommentsWidget.cpp index 3f7acac2..29f98025 100644 --- a/src/widgets/CommentsWidget.cpp +++ b/src/widgets/CommentsWidget.cpp @@ -8,13 +8,13 @@ #include CommentsModel::CommentsModel(QList *comments, - QList *nestedComments, - QObject *parent) + QList *nestedComments, QObject *parent) : AddressableItemModel<>(parent), comments(comments), nestedComments(nestedComments), nested(false) -{} +{ +} bool CommentsModel::isNested() const { @@ -45,7 +45,7 @@ RVA CommentsModel::address(const QModelIndex &index) const QModelIndex CommentsModel::index(int row, int column, const QModelIndex &parent) const { if (!parent.isValid()) { - return createIndex(row, column, (quintptr) 0); + return createIndex(row, column, (quintptr)0); } return createIndex(row, column, (quintptr)(parent.row() + 1)); @@ -75,9 +75,8 @@ int CommentsModel::rowCount(const QModelIndex &parent) const int CommentsModel::columnCount(const QModelIndex &) const { - return (isNested() - ? static_cast(CommentsModel::NestedColumnCount) - : static_cast(CommentsModel::ColumnCount)); + return (isNested() ? static_cast(CommentsModel::NestedColumnCount) + : static_cast(CommentsModel::ColumnCount)); } QVariant CommentsModel::data(const QModelIndex &index, int role) const @@ -214,13 +213,15 @@ bool CommentsProxyModel::lessThan(const QModelIndex &left, const QModelIndex &ri return false; auto leftComment = left.data(CommentsModel::CommentDescriptionRole).value(); - auto rightComment = right.data(CommentsModel::CommentDescriptionRole).value(); + auto rightComment = + right.data(CommentsModel::CommentDescriptionRole).value(); switch (left.column()) { case CommentsModel::OffsetColumn: return leftComment.offset < rightComment.offset; case CommentsModel::FunctionColumn: - return Core()->cmdFunctionAt(leftComment.offset) < Core()->cmdFunctionAt(rightComment.offset); + return Core()->cmdFunctionAt(leftComment.offset) + < Core()->cmdFunctionAt(rightComment.offset); case CommentsModel::CommentColumn: return leftComment.name < rightComment.name; default: @@ -230,10 +231,10 @@ bool CommentsProxyModel::lessThan(const QModelIndex &left, const QModelIndex &ri return false; } -CommentsWidget::CommentsWidget(MainWindow *main) : - ListDockWidget(main), - actionHorizontal(tr("Horizontal"), this), - actionVertical(tr("Vertical"), this) +CommentsWidget::CommentsWidget(MainWindow *main) + : ListDockWidget(main), + actionHorizontal(tr("Horizontal"), this), + actionVertical(tr("Vertical"), this) { setWindowTitle(tr("Comments")); setObjectName("CommentsWidget"); @@ -253,11 +254,10 @@ CommentsWidget::CommentsWidget(MainWindow *main) : connect(&actionVertical, &QAction::toggled, this, &CommentsWidget::onActionVerticalToggled); titleContextMenu->addActions(viewTypeGroup->actions()); - actionHorizontal.setChecked(true); this->setContextMenuPolicy(Qt::CustomContextMenu); - connect(this, &QWidget::customContextMenuRequested, - this, &CommentsWidget::showTitleContextMenu); + connect(this, &QWidget::customContextMenuRequested, this, + &CommentsWidget::showTitleContextMenu); connect(Core(), &CutterCore::codeRebased, this, &CommentsWidget::refreshTree); connect(Core(), &CutterCore::commentsChanged, this, &CommentsWidget::refreshTree); @@ -300,7 +300,7 @@ void CommentsWidget::refreshTree() auto nestedCommentIt = nestedCommentMapping.find(fcnName); if (nestedCommentIt == nestedCommentMapping.end()) { nestedCommentMapping.insert(fcnName, nestedComments.size()); - nestedComments.push_back({fcnName, offset, {comment}}); + nestedComments.push_back({ fcnName, offset, { comment } }); } else { auto &commentGroup = nestedComments[nestedCommentIt.value()]; commentGroup.comments.append(comment); @@ -311,4 +311,3 @@ void CommentsWidget::refreshTree() qhelpers::adjustColumns(ui->treeView, 3, 0); } - diff --git a/src/widgets/CommentsWidget.h b/src/widgets/CommentsWidget.h index 6b2e75aa..1f1d7e8e 100644 --- a/src/widgets/CommentsWidget.h +++ b/src/widgets/CommentsWidget.h @@ -38,11 +38,11 @@ public: enum NestedColumn { OffsetNestedColumn = 0, CommentNestedColumn, NestedColumnCount }; enum Role { CommentDescriptionRole = Qt::UserRole, FunctionRole }; - CommentsModel(QList *comments, - QList *nestedComments, + CommentsModel(QList *comments, QList *nestedComments, QObject *parent = nullptr); - QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const override; + QModelIndex index(int row, int column, + const QModelIndex &parent = QModelIndex()) const override; QModelIndex parent(const QModelIndex &index) const override; int rowCount(const QModelIndex &parent = QModelIndex()) const override; diff --git a/src/widgets/ConsoleWidget.cpp b/src/widgets/ConsoleWidget.cpp index 99de903c..ad75e999 100644 --- a/src/widgets/ConsoleWidget.cpp +++ b/src/widgets/ConsoleWidget.cpp @@ -17,18 +17,18 @@ #include "WidgetShortcuts.h" #ifdef Q_OS_WIN -#include -#define dup2 _dup2 -#define dup _dup -#define fileno _fileno -#define fdopen _fdopen -#define PIPE_SIZE 65536 // Match Linux size -#define PIPE_NAME "\\\\.\\pipe\\cutteroutput-%1" +# include +# define dup2 _dup2 +# define dup _dup +# define fileno _fileno +# define fdopen _fdopen +# define PIPE_SIZE 65536 // Match Linux size +# define PIPE_NAME "\\\\.\\pipe\\cutteroutput-%1" #else -#include -#define PIPE_READ (0) -#define PIPE_WRITE (1) -#define STDIN_PIPE_NAME "%1/cutter-stdin-%2" +# include +# define PIPE_READ (0) +# define PIPE_WRITE (1) +# define STDIN_PIPE_NAME "%1/cutter-stdin-%2" #endif #define CONSOLE_RIZIN_INPUT ("Rizin Console") @@ -38,15 +38,15 @@ static const int invalidHistoryPos = -1; static const char *consoleWrapSettingsKey = "console.wrap"; -ConsoleWidget::ConsoleWidget(MainWindow *main) : - CutterDockWidget(main), - ui(new Ui::ConsoleWidget), - debugOutputEnabled(true), - maxHistoryEntries(100), - lastHistoryPosition(invalidHistoryPos), - completer(nullptr), - historyUpShortcut(nullptr), - historyDownShortcut(nullptr) +ConsoleWidget::ConsoleWidget(MainWindow *main) + : CutterDockWidget(main), + ui(new Ui::ConsoleWidget), + debugOutputEnabled(true), + maxHistoryEntries(100), + lastHistoryPosition(invalidHistoryPos), + completer(nullptr), + historyUpShortcut(nullptr), + historyDownShortcut(nullptr) { ui->setupUi(this); @@ -63,9 +63,10 @@ ConsoleWidget::ConsoleWidget(MainWindow *main) : // Ctrl+` and ';' to toggle console widget QAction *toggleConsole = toggleViewAction(); QList toggleShortcuts; - toggleShortcuts << widgetShortcuts["ConsoleWidget"] << widgetShortcuts["ConsoleWidgetAlternative"]; + toggleShortcuts << widgetShortcuts["ConsoleWidget"] + << widgetShortcuts["ConsoleWidgetAlternative"]; toggleConsole->setShortcuts(toggleShortcuts); - connect(toggleConsole, &QAction::triggered, this, [this, toggleConsole](){ + connect(toggleConsole, &QAction::triggered, this, [this, toggleConsole]() { if (toggleConsole->isChecked()) { widgetToFocusOnRaise()->setFocus(); } @@ -83,9 +84,7 @@ ConsoleWidget::ConsoleWidget(MainWindow *main) : actionWrapLines = new QAction(tr("Wrap Lines"), ui->outputTextEdit); actionWrapLines->setCheckable(true); setWrap(QSettings().value(consoleWrapSettingsKey, true).toBool()); - connect(actionWrapLines, &QAction::triggered, this, [this] (bool checked) { - setWrap(checked); - }); + connect(actionWrapLines, &QAction::triggered, this, [this](bool checked) { setWrap(checked); }); actions.append(actionWrapLines); // Completion @@ -101,15 +100,17 @@ ConsoleWidget::ConsoleWidget(MainWindow *main) : // Set console output context menu ui->outputTextEdit->setContextMenuPolicy(Qt::CustomContextMenu); - connect(ui->outputTextEdit, &QWidget::customContextMenuRequested, - this, &ConsoleWidget::showCustomContextMenu); + connect(ui->outputTextEdit, &QWidget::customContextMenuRequested, this, + &ConsoleWidget::showCustomContextMenu); // Esc clears rzInputLineEdit and debugeeInputLineEdit (like OmniBar) - QShortcut *rizin_clear_shortcut = new QShortcut(QKeySequence(Qt::Key_Escape), ui->rzInputLineEdit); + QShortcut *rizin_clear_shortcut = + new QShortcut(QKeySequence(Qt::Key_Escape), ui->rzInputLineEdit); connect(rizin_clear_shortcut, &QShortcut::activated, this, &ConsoleWidget::clear); rizin_clear_shortcut->setContext(Qt::WidgetShortcut); - QShortcut *debugee_clear_shortcut = new QShortcut(QKeySequence(Qt::Key_Escape), ui->debugeeInputLineEdit); + QShortcut *debugee_clear_shortcut = + new QShortcut(QKeySequence(Qt::Key_Escape), ui->debugeeInputLineEdit); connect(debugee_clear_shortcut, &QShortcut::activated, this, &ConsoleWidget::clear); debugee_clear_shortcut->setContext(Qt::WidgetShortcut); @@ -125,15 +126,15 @@ ConsoleWidget::ConsoleWidget(MainWindow *main) : QShortcut *completionShortcut = new QShortcut(QKeySequence(Qt::Key_Tab), ui->rzInputLineEdit); connect(completionShortcut, &QShortcut::activated, this, &ConsoleWidget::triggerCompletion); - connect(ui->rzInputLineEdit, &QLineEdit::editingFinished, this, &ConsoleWidget::disableCompletion); + connect(ui->rzInputLineEdit, &QLineEdit::editingFinished, this, + &ConsoleWidget::disableCompletion); connect(Config(), &Configuration::fontsUpdated, this, &ConsoleWidget::setupFont); - connect(ui->inputCombo, - static_cast(&QComboBox::currentIndexChanged), + connect(ui->inputCombo, static_cast(&QComboBox::currentIndexChanged), this, &ConsoleWidget::onIndexChange); - connect(Core(), &CutterCore::debugTaskStateChanged, this, [ = ]() { + connect(Core(), &CutterCore::debugTaskStateChanged, this, [=]() { if (Core()->isRedirectableDebugee()) { ui->inputCombo->setVisible(true); } else { @@ -160,7 +161,7 @@ ConsoleWidget::~ConsoleWidget() bool ConsoleWidget::eventFilter(QObject *obj, QEvent *event) { - if(completer && obj == completer->popup() && + if (completer && obj == completer->popup() && // disable up/down shortcuts if completer is shown (event->type() == QEvent::Type::Show || event->type() == QEvent::Type::Hide)) { bool enabled = !completer->popup()->isVisible(); @@ -226,21 +227,21 @@ void ConsoleWidget::executeCommand(const QString &command) addOutput(cmd_line); RVA oldOffset = Core()->getOffset(); - commandTask = QSharedPointer(new CommandTask(command, CommandTask::ColorMode::MODE_256, true)); - connect(commandTask.data(), &CommandTask::finished, this, [this, cmd_line, - command, oldOffset] (const QString & result) { + commandTask = QSharedPointer( + new CommandTask(command, CommandTask::ColorMode::MODE_256, true)); + connect(commandTask.data(), &CommandTask::finished, this, + [this, cmd_line, command, oldOffset](const QString &result) { + ui->outputTextEdit->appendHtml(result); + scrollOutputToEnd(); + historyAdd(command); + commandTask.clear(); + ui->rzInputLineEdit->setEnabled(true); + ui->rzInputLineEdit->setFocus(); - ui->outputTextEdit->appendHtml(result); - scrollOutputToEnd(); - historyAdd(command); - commandTask.clear(); - ui->rzInputLineEdit->setEnabled(true); - ui->rzInputLineEdit->setFocus(); - - if (oldOffset != Core()->getOffset()) { - Core()->updateSeek(); - } - }); + if (oldOffset != Core()->getOffset()) { + Core()->updateSeek(); + } + }); Core()->getAsyncTaskManager()->start(commandTask); } @@ -275,7 +276,8 @@ void ConsoleWidget::setWrap(bool wrap) { QSettings().setValue(consoleWrapSettingsKey, wrap); actionWrapLines->setChecked(wrap); - ui->outputTextEdit->setLineWrapMode(wrap ? QPlainTextEdit::WidgetWidth: QPlainTextEdit::NoWrap); + ui->outputTextEdit->setLineWrapMode(wrap ? QPlainTextEdit::WidgetWidth + : QPlainTextEdit::NoWrap); } void ConsoleWidget::on_rzInputLineEdit_returnPressed() @@ -318,7 +320,7 @@ void ConsoleWidget::historyNext() if (!history.isEmpty()) { if (lastHistoryPosition > invalidHistoryPos) { if (lastHistoryPosition >= history.size()) { - lastHistoryPosition = history.size() - 1 ; + lastHistoryPosition = history.size() - 1; } --lastHistoryPosition; @@ -328,8 +330,6 @@ void ConsoleWidget::historyNext() } else { ui->rzInputLineEdit->clear(); } - - } } } @@ -436,7 +436,7 @@ void ConsoleWidget::processQueuedOutput() // Haiku doesn't have O_ASYNC #ifdef Q_OS_HAIKU -#define O_ASYNC O_NONBLOCK +# define O_ASYNC O_NONBLOCK #endif void ConsoleWidget::redirectOutput() @@ -455,9 +455,10 @@ void ConsoleWidget::redirectOutput() #ifdef Q_OS_WIN QString pipeName = QString::fromLatin1(PIPE_NAME).arg(QUuid::createUuid().toString()); - SECURITY_ATTRIBUTES attributes = {sizeof(SECURITY_ATTRIBUTES), 0, false}; - hWrite = CreateNamedPipeW((wchar_t *)pipeName.utf16(), PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED, - PIPE_TYPE_BYTE | PIPE_WAIT, 1, PIPE_SIZE, PIPE_SIZE, 0, &attributes); + SECURITY_ATTRIBUTES attributes = { sizeof(SECURITY_ATTRIBUTES), 0, false }; + hWrite = + CreateNamedPipeW((wchar_t *)pipeName.utf16(), PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED, + PIPE_TYPE_BYTE | PIPE_WAIT, 1, PIPE_SIZE, PIPE_SIZE, 0, &attributes); int writeFd = _open_osfhandle((intptr_t)hWrite, _O_WRONLY | _O_TEXT); dup2(writeFd, fileno(stdout)); @@ -467,7 +468,7 @@ void ConsoleWidget::redirectOutput() #else pipe(redirectPipeFds); stdinFifoPath = QString(STDIN_PIPE_NAME).arg(QDir::tempPath(), QUuid::createUuid().toString()); - mkfifo(stdinFifoPath.toStdString().c_str(), (mode_t) 0777); + mkfifo(stdinFifoPath.toStdString().c_str(), (mode_t)0777); stdinFile = open(stdinFifoPath.toStdString().c_str(), O_RDWR | O_ASYNC); dup2(stdinFile, fileno(stdin)); diff --git a/src/widgets/ConsoleWidget.h b/src/widgets/ConsoleWidget.h index bdc0e1f6..4fecffbc 100644 --- a/src/widgets/ConsoleWidget.h +++ b/src/widgets/ConsoleWidget.h @@ -28,19 +28,13 @@ public: ~ConsoleWidget(); - void setDebugOutputEnabled(bool enabled) - { - debugOutputEnabled = enabled; - } + void setDebugOutputEnabled(bool enabled) { debugOutputEnabled = enabled; } - void setMaxHistoryEntries(int max) - { - maxHistoryEntries = max; - } + void setMaxHistoryEntries(int max) { maxHistoryEntries = max; } protected: bool eventFilter(QObject *obj, QEvent *event) override; - QWidget* widgetToFocusOnRaise() override; + QWidget *widgetToFocusOnRaise() override; public slots: void focusInputLineEdit(); @@ -105,7 +99,7 @@ private: FILE *origStderr = nullptr; FILE *origStdout = nullptr; FILE *origStdin = nullptr; - QLocalSocket *pipeSocket = nullptr; + QLocalSocket *pipeSocket = nullptr; #ifdef Q_OS_WIN HANDLE hRead; HANDLE hWrite; diff --git a/src/widgets/CutterDockWidget.cpp b/src/widgets/CutterDockWidget.cpp index d29bc08d..3c75a3d1 100644 --- a/src/widgets/CutterDockWidget.cpp +++ b/src/widgets/CutterDockWidget.cpp @@ -4,14 +4,9 @@ #include #include -CutterDockWidget::CutterDockWidget(MainWindow *parent, QAction *) - : CutterDockWidget(parent) -{ -} +CutterDockWidget::CutterDockWidget(MainWindow *parent, QAction *) : CutterDockWidget(parent) {} -CutterDockWidget::CutterDockWidget(MainWindow *parent) : - QDockWidget(parent), - mainWindow(parent) +CutterDockWidget::CutterDockWidget(MainWindow *parent) : QDockWidget(parent), mainWindow(parent) { // Install event filter to catch redraw widgets when needed installEventFilter(this); @@ -23,12 +18,9 @@ CutterDockWidget::~CutterDockWidget() = default; bool CutterDockWidget::eventFilter(QObject *object, QEvent *event) { - if (event->type() == QEvent::FocusIn - || event->type() == QEvent::ZOrderChange - || event->type() == QEvent::Paint - || event->type() == QEvent::Close - || event->type() == QEvent::Show - || event->type() == QEvent::Hide) { + if (event->type() == QEvent::FocusIn || event->type() == QEvent::ZOrderChange + || event->type() == QEvent::Paint || event->type() == QEvent::Close + || event->type() == QEvent::Show || event->type() == QEvent::Hide) { updateIsVisibleToUser(); } return QDockWidget::eventFilter(object, event); @@ -39,9 +31,7 @@ QVariantMap CutterDockWidget::serializeViewProprties() return {}; } -void CutterDockWidget::deserializeViewProperties(const QVariantMap &) -{ -} +void CutterDockWidget::deserializeViewProperties(const QVariantMap &) {} void CutterDockWidget::ignoreVisibilityStatus(bool ignore) { @@ -92,7 +82,8 @@ void CutterDockWidget::closeEvent(QCloseEvent *event) mainWindow->removeWidget(this); } - // remove parent, otherwise dock layout may still decide to use this widget which is about to be deleted + // remove parent, otherwise dock layout may still decide to use this widget which is about + // to be deleted setParent(nullptr); deleteLater(); diff --git a/src/widgets/CutterDockWidget.h b/src/widgets/CutterDockWidget.h index d9d1ec9d..9e283517 100644 --- a/src/widgets/CutterDockWidget.h +++ b/src/widgets/CutterDockWidget.h @@ -19,16 +19,17 @@ public: explicit CutterDockWidget(MainWindow *parent); ~CutterDockWidget() override; bool eventFilter(QObject *object, QEvent *event) override; - bool isVisibleToUser() { return isVisibleToUserCurrent; } + bool isVisibleToUser() { return isVisibleToUserCurrent; } /** * @brief Set whether the Widget should be deleted after it is closed. * This is especially important for extra widgets. */ - void setTransient(bool v) { isTransient = v; } + void setTransient(bool v) { isTransient = v; } /** - * @brief Convenience method for creating and registering a RefreshDeferrer without any parameters + * @brief Convenience method for creating and registering a RefreshDeferrer without any + * parameters * @param refreshNowFunc lambda taking no parameters, called when a refresh should occur */ template @@ -36,26 +37,29 @@ public: { auto *deferrer = new RefreshDeferrer(nullptr, this); deferrer->registerFor(this); - connect(deferrer, &RefreshDeferrer::refreshNow, this, [refreshNowFunc](const RefreshDeferrerParamsResult) { - refreshNowFunc(); - }); + connect(deferrer, &RefreshDeferrer::refreshNow, this, + [refreshNowFunc](const RefreshDeferrerParamsResult) { refreshNowFunc(); }); return deferrer; } /** - * @brief Convenience method for creating and registering a RefreshDeferrer with a replacing Accumulator + * @brief Convenience method for creating and registering a RefreshDeferrer with a replacing + * Accumulator * @param replaceIfNull passed to the ReplacingRefreshDeferrerAccumulator - * @param refreshNowFunc lambda taking a single parameter of type ParamResult, called when a refresh should occur + * @param refreshNowFunc lambda taking a single parameter of type ParamResult, called when a + * refresh should occur */ template RefreshDeferrer *createReplacingRefreshDeferrer(bool replaceIfNull, Func refreshNowFunc) { - auto *deferrer = new RefreshDeferrer(new ReplacingRefreshDeferrerAccumulator(replaceIfNull), this); + auto *deferrer = new RefreshDeferrer( + new ReplacingRefreshDeferrerAccumulator(replaceIfNull), this); deferrer->registerFor(this); - connect(deferrer, &RefreshDeferrer::refreshNow, this, [refreshNowFunc](const RefreshDeferrerParamsResult paramsResult) { - auto *result = static_cast(paramsResult); - refreshNowFunc(result); - }); + connect(deferrer, &RefreshDeferrer::refreshNow, this, + [refreshNowFunc](const RefreshDeferrerParamsResult paramsResult) { + auto *result = static_cast(paramsResult); + refreshNowFunc(result); + }); return deferrer; } /** @@ -102,7 +106,7 @@ public slots: void toggleDockWidget(bool show); protected: - virtual QWidget* widgetToFocusOnRaise(); + virtual QWidget *widgetToFocusOnRaise(); void closeEvent(QCloseEvent *event) override; QString getDockNumber(); diff --git a/src/widgets/CutterGraphView.cpp b/src/widgets/CutterGraphView.cpp index b02e10df..9de48ce1 100644 --- a/src/widgets/CutterGraphView.cpp +++ b/src/widgets/CutterGraphView.cpp @@ -10,7 +10,6 @@ #include #include - static const int KEY_ZOOM_IN = Qt::Key_Plus + Qt::ControlModifier; static const int KEY_ZOOM_OUT = Qt::Key_Minus + Qt::ControlModifier; static const int KEY_ZOOM_RESET = Qt::Key_Equal + Qt::ControlModifier; @@ -18,16 +17,16 @@ static const int KEY_ZOOM_RESET = Qt::Key_Equal + Qt::ControlModifier; static const uint64_t BITMPA_EXPORT_WARNING_SIZE = 32 * 1024 * 1024; #ifndef NDEBUG -#define GRAPH_GRID_DEBUG_MODES true +# define GRAPH_GRID_DEBUG_MODES true #else -#define GRAPH_GRID_DEBUG_MODES false +# define GRAPH_GRID_DEBUG_MODES false #endif CutterGraphView::CutterGraphView(QWidget *parent) - : GraphView(parent) - , mFontMetrics(nullptr) - , actionExportGraph(tr("Export Graph"), this) - , graphLayout(GraphView::Layout::GridMedium) + : GraphView(parent), + mFontMetrics(nullptr), + actionExportGraph(tr("Export Graph"), this), + graphLayout(GraphView::Layout::GridMedium) { connect(Core(), &CutterCore::graphOptionsChanged, this, &CutterGraphView::refreshView); connect(Config(), &Configuration::colorsUpdated, this, &CutterGraphView::colorsUpdatedSlot); @@ -43,26 +42,28 @@ CutterGraphView::CutterGraphView(QWidget *parent) horizontalLayoutAction->setCheckable(true); static const std::pair LAYOUT_CONFIG[] = { - {tr("Grid narrow"), GraphView::Layout::GridNarrow} - , {tr("Grid medium"), GraphView::Layout::GridMedium} - , {tr("Grid wide"), GraphView::Layout::GridWide} + { tr("Grid narrow"), GraphView::Layout::GridNarrow }, + { tr("Grid medium"), GraphView::Layout::GridMedium }, + { tr("Grid wide"), GraphView::Layout::GridWide } #if GRAPH_GRID_DEBUG_MODES - , {"GridAAA", GraphView::Layout::GridAAA} - , {"GridAAB", GraphView::Layout::GridAAB} - , {"GridABA", GraphView::Layout::GridABA} - , {"GridABB", GraphView::Layout::GridABB} - , {"GridBAA", GraphView::Layout::GridBAA} - , {"GridBAB", GraphView::Layout::GridBAB} - , {"GridBBA", GraphView::Layout::GridBBA} - , {"GridBBB", GraphView::Layout::GridBBB} + , + { "GridAAA", GraphView::Layout::GridAAA }, + { "GridAAB", GraphView::Layout::GridAAB }, + { "GridABA", GraphView::Layout::GridABA }, + { "GridABB", GraphView::Layout::GridABB }, + { "GridBAA", GraphView::Layout::GridBAA }, + { "GridBAB", GraphView::Layout::GridBAB }, + { "GridBBA", GraphView::Layout::GridBBA }, + { "GridBBB", GraphView::Layout::GridBBB } #endif #ifdef CUTTER_ENABLE_GRAPHVIZ - , {tr("Graphviz polyline"), GraphView::Layout::GraphvizPolyline} - , {tr("Graphviz ortho"), GraphView::Layout::GraphvizOrtho} - , {tr("Graphviz sfdp"), GraphView::Layout::GraphvizSfdp} - , {tr("Graphviz neato"), GraphView::Layout::GraphvizNeato} - , {tr("Graphviz twopi"), GraphView::Layout::GraphvizTwoPi} - , {tr("Graphviz circo"), GraphView::Layout::GraphvizCirco} + , + { tr("Graphviz polyline"), GraphView::Layout::GraphvizPolyline }, + { tr("Graphviz ortho"), GraphView::Layout::GraphvizOrtho }, + { tr("Graphviz sfdp"), GraphView::Layout::GraphvizSfdp }, + { tr("Graphviz neato"), GraphView::Layout::GraphvizNeato }, + { tr("Graphviz twopi"), GraphView::Layout::GraphvizTwoPi }, + { tr("Graphviz circo"), GraphView::Layout::GraphvizCirco } #endif }; layoutMenu->addSeparator(); @@ -79,7 +80,6 @@ CutterGraphView::CutterGraphView(QWidget *parent) this->graphLayout = layout; updateLayout(); }); - } layoutMenu->addActions(layoutGroup->actions()); @@ -206,8 +206,8 @@ bool CutterGraphView::event(QEvent *event) case QEvent::ShortcutOverride: { QKeyEvent *keyEvent = static_cast(event); int key = keyEvent->key() + keyEvent->modifiers(); - if (key == KEY_ZOOM_OUT || key == KEY_ZOOM_RESET - || key == KEY_ZOOM_IN || (key == (KEY_ZOOM_IN | Qt::ShiftModifier))) { + if (key == KEY_ZOOM_OUT || key == KEY_ZOOM_RESET || key == KEY_ZOOM_IN + || (key == (KEY_ZOOM_IN | Qt::ShiftModifier))) { event->accept(); return true; } @@ -246,8 +246,7 @@ bool CutterGraphView::gestureEvent(QGestureEvent *event) return false; } - if (auto gesture = - static_cast(event->gesture(Qt::PinchGesture))) { + if (auto gesture = static_cast(event->gesture(Qt::PinchGesture))) { auto changeFlags = gesture->changeFlags(); if (changeFlags & QPinchGesture::ScaleFactorChanged) { @@ -297,14 +296,9 @@ void CutterGraphView::resizeEvent(QResizeEvent *event) emit resized(); } -void CutterGraphView::saveCurrentBlock() -{ -} - -void CutterGraphView::restoreCurrentBlock() -{ -} +void CutterGraphView::saveCurrentBlock() {} +void CutterGraphView::restoreCurrentBlock() {} void CutterGraphView::mousePressEvent(QMouseEvent *event) { @@ -369,11 +363,11 @@ void CutterGraphView::exportGraph(QString filePath, GraphExportType type, QStrin } void CutterGraphView::exportRizinGraphvizGraph(QString filePath, QString type, QString graphCommand, - RVA address) + RVA address) { TempConfig tempConfig; tempConfig.set("graph.gv.format", type); - qWarning() << Core()->cmdRawAt(QString("%0w \"%1\"").arg(graphCommand).arg(filePath), address); + qWarning() << Core()->cmdRawAt(QString("%0w \"%1\"").arg(graphCommand).arg(filePath), address); } void CutterGraphView::exportRzTextGraph(QString filePath, QString graphCommand, RVA address) @@ -401,36 +395,41 @@ bool CutterGraphView::graphIsBitamp(CutterGraphView::GraphExportType type) } } - Q_DECLARE_METATYPE(CutterGraphView::GraphExportType); void CutterGraphView::showExportGraphDialog(QString defaultName, QString graphCommand, RVA address) { QVector types = { - {tr("PNG (*.png)"), "png", QVariant::fromValue(GraphExportType::Png)}, - {tr("JPEG (*.jpg)"), "jpg", QVariant::fromValue(GraphExportType::Jpeg)}, - {tr("SVG (*.svg)"), "svg", QVariant::fromValue(GraphExportType::Svg)} + { tr("PNG (*.png)"), "png", QVariant::fromValue(GraphExportType::Png) }, + { tr("JPEG (*.jpg)"), "jpg", QVariant::fromValue(GraphExportType::Jpeg) }, + { tr("SVG (*.svg)"), "svg", QVariant::fromValue(GraphExportType::Svg) } }; bool rzGraphExports = !graphCommand.isEmpty(); if (rzGraphExports) { types.append({ - {tr("Graphviz dot (*.dot)"), "dot", QVariant::fromValue(GraphExportType::GVDot)}, - {tr("Graph Modelling Language (*.gml)"), "gml", QVariant::fromValue(GraphExportType::RzGml)}, - {tr("RZ JSON (*.json)"), "json", QVariant::fromValue(GraphExportType::RzJson)}, - {tr("SDB key-value (*.txt)"), "txt", QVariant::fromValue(GraphExportType::RzSDBKeyValue)}, + { tr("Graphviz dot (*.dot)"), "dot", QVariant::fromValue(GraphExportType::GVDot) }, + { tr("Graph Modelling Language (*.gml)"), "gml", + QVariant::fromValue(GraphExportType::RzGml) }, + { tr("RZ JSON (*.json)"), "json", QVariant::fromValue(GraphExportType::RzJson) }, + { tr("SDB key-value (*.txt)"), "txt", + QVariant::fromValue(GraphExportType::RzSDBKeyValue) }, }); bool hasGraphviz = !QStandardPaths::findExecutable("dot").isEmpty() - || !QStandardPaths::findExecutable("xdot").isEmpty(); + || !QStandardPaths::findExecutable("xdot").isEmpty(); if (hasGraphviz) { - types.append({ - {tr("Graphviz json (*.json)"), "json", QVariant::fromValue(GraphExportType::GVJson)}, - {tr("Graphviz gif (*.gif)"), "gif", QVariant::fromValue(GraphExportType::GVGif)}, - {tr("Graphviz png (*.png)"), "png", QVariant::fromValue(GraphExportType::GVPng)}, - {tr("Graphviz jpg (*.jpg)"), "jpg", QVariant::fromValue(GraphExportType::GVJpeg)}, - {tr("Graphviz PostScript (*.ps)"), "ps", QVariant::fromValue(GraphExportType::GVPostScript)}, - {tr("Graphviz svg (*.svg)"), "svg", QVariant::fromValue(GraphExportType::GVSvg)} - }); + types.append({ { tr("Graphviz json (*.json)"), "json", + QVariant::fromValue(GraphExportType::GVJson) }, + { tr("Graphviz gif (*.gif)"), "gif", + QVariant::fromValue(GraphExportType::GVGif) }, + { tr("Graphviz png (*.png)"), "png", + QVariant::fromValue(GraphExportType::GVPng) }, + { tr("Graphviz jpg (*.jpg)"), "jpg", + QVariant::fromValue(GraphExportType::GVJpeg) }, + { tr("Graphviz PostScript (*.ps)"), "ps", + QVariant::fromValue(GraphExportType::GVPostScript) }, + { tr("Graphviz svg (*.svg)"), "svg", + QVariant::fromValue(GraphExportType::GVSvg) } }); } } @@ -451,10 +450,13 @@ void CutterGraphView::showExportGraphDialog(QString defaultName, QString graphCo if (graphIsBitamp(exportType)) { uint64_t bitmapSize = uint64_t(width) * uint64_t(height); if (bitmapSize > BITMPA_EXPORT_WARNING_SIZE) { - auto answer = QMessageBox::question(this, - tr("Graph Export"), - tr("Do you really want to export %1 x %2 = %3 pixel bitmap image? Consider using different format.") - .arg(width).arg(height).arg(bitmapSize)); + auto answer = + QMessageBox::question(this, tr("Graph Export"), + tr("Do you really want to export %1 x %2 = %3 pixel " + "bitmap image? Consider using different format.") + .arg(width) + .arg(height) + .arg(bitmapSize)); if (answer != QMessageBox::Yes) { return; } @@ -463,5 +465,4 @@ void CutterGraphView::showExportGraphDialog(QString defaultName, QString graphCo QString filePath = dialog.selectedFiles().first(); exportGraph(filePath, exportType, graphCommand, address); - } diff --git a/src/widgets/CutterGraphView.h b/src/widgets/CutterGraphView.h index 8a075b45..637b1f4d 100644 --- a/src/widgets/CutterGraphView.h +++ b/src/widgets/CutterGraphView.h @@ -1,7 +1,6 @@ #ifndef CUTTER_GRAPHVIEW_H #define CUTTER_GRAPHVIEW_H - #include #include #include @@ -23,15 +22,26 @@ public: virtual bool event(QEvent *event) override; enum class GraphExportType { - Png, Jpeg, Svg, GVDot, GVJson, - GVGif, GVPng, GVJpeg, GVPostScript, GVSvg, - RzGml, RzSDBKeyValue, RzJson + Png, + Jpeg, + Svg, + GVDot, + GVJson, + GVGif, + GVPng, + GVJpeg, + GVPostScript, + GVSvg, + RzGml, + RzSDBKeyValue, + RzJson }; /** * @brief Export graph to a file in the specified format * @param filePath * @param type export type, GV* and Rz* types require \p graphCommand - * @param graphCommand rizin graph printing command without type, not required for direct image export + * @param graphCommand rizin graph printing command without type, not required for direct image + * export * @param address object address for commands like agf */ void exportGraph(QString filePath, GraphExportType type, QString graphCommand = "", @@ -45,7 +55,8 @@ public: * @param graphCommand rizin command without type, for example agf * @param address object address if required by command */ - void exportRizinGraphvizGraph(QString filePath, QString type, QString graphCommand, RVA address); + void exportRizinGraphvizGraph(QString filePath, QString type, QString graphCommand, + RVA address); /** * @brief Export graph in one of the text formats supported by rizin json, gml, SDB key-value * @param filePath output file path @@ -57,8 +68,9 @@ public: /** * @brief Show graph export dialog. * @param defaultName - default file name in the export dialog - * @param graphCommand - rizin graph commmand with graph type and without export type, for example afC. Leave empty - * for non-rizin graphs. In such case only direct image export will be available. + * @param graphCommand - rizin graph commmand with graph type and without export type, for + * example afC. Leave empty for non-rizin graphs. In such case only direct image export will be + * available. * @param address - object address if relevant for \p graphCommand */ void showExportGraphDialog(QString defaultName, QString graphCommand = "", @@ -84,6 +96,7 @@ signals: void viewZoomed(); void graphMoved(); void resized(); + protected: void mousePressEvent(QMouseEvent *event) override; void mouseMoveEvent(QMouseEvent *event) override; @@ -93,14 +106,14 @@ protected: /** * @brief Save the the currently viewed or displayed block. - * Called before reloading graph. Override to this to implement graph specific logic for what block is selected. - * Default implementation does nothing. + * Called before reloading graph. Override to this to implement graph specific logic for what + * block is selected. Default implementation does nothing. */ virtual void saveCurrentBlock(); /** * @brief Restore view focus and block last saved using saveCurrentBlock(). - * Called after the graph is reloaded. Default implementation does nothing. Can center the view if the new graph - * displays completely different content and the matching node doesn't exist. + * Called after the graph is reloaded. Default implementation does nothing. Can center the view + * if the new graph displays completely different content and the matching node doesn't exist. */ virtual void restoreCurrentBlock(); @@ -144,6 +157,7 @@ protected: GraphView::Layout graphLayout; QMenu *layoutMenu; QAction *horizontalLayoutAction; + private: void colorsUpdatedSlot(); }; diff --git a/src/widgets/CutterTreeView.cpp b/src/widgets/CutterTreeView.cpp index a021182b..f26fc08c 100644 --- a/src/widgets/CutterTreeView.cpp +++ b/src/widgets/CutterTreeView.cpp @@ -1,9 +1,7 @@ #include "CutterTreeView.h" #include "ui_CutterTreeView.h" -CutterTreeView::CutterTreeView(QWidget *parent) : - QTreeView(parent), - ui(new Ui::CutterTreeView()) +CutterTreeView::CutterTreeView(QWidget *parent) : QTreeView(parent), ui(new Ui::CutterTreeView()) { ui->setupUi(this); this->setSelectionMode(QAbstractItemView::ExtendedSelection); diff --git a/src/widgets/CutterTreeView.h b/src/widgets/CutterTreeView.h index f4b34eb4..46dfcccd 100644 --- a/src/widgets/CutterTreeView.h +++ b/src/widgets/CutterTreeView.h @@ -23,4 +23,4 @@ private: std::unique_ptr ui; }; -#endif //CUTTERTREEVIEW_H +#endif // CUTTERTREEVIEW_H diff --git a/src/widgets/CutterTreeWidget.cpp b/src/widgets/CutterTreeWidget.cpp index 09009d04..03d45ccb 100644 --- a/src/widgets/CutterTreeWidget.cpp +++ b/src/widgets/CutterTreeWidget.cpp @@ -1,14 +1,11 @@ #include "CutterTreeWidget.h" #include "core/MainWindow.h" -CutterTreeWidget::CutterTreeWidget(QObject *parent) : - QObject(parent), - bar(nullptr) -{} +CutterTreeWidget::CutterTreeWidget(QObject *parent) : QObject(parent), bar(nullptr) {} void CutterTreeWidget::addStatusBar(QVBoxLayout *pos) { - if(!bar) { + if (!bar) { bar = new QStatusBar; QSizePolicy sizePolicy(QSizePolicy::Preferred, QSizePolicy::Maximum); bar->setSizePolicy(sizePolicy); @@ -18,7 +15,7 @@ void CutterTreeWidget::addStatusBar(QVBoxLayout *pos) void CutterTreeWidget::showItemsNumber(int count) { - if(bar){ + if (bar) { bar->showMessage(tr("%1 Items").arg(count)); } } diff --git a/src/widgets/CutterTreeWidget.h b/src/widgets/CutterTreeWidget.h index 00fe7e9b..68664fa5 100644 --- a/src/widgets/CutterTreeWidget.h +++ b/src/widgets/CutterTreeWidget.h @@ -22,6 +22,5 @@ public: private: QStatusBar *bar; - }; #endif // CUTTERTREEWIDGET_H diff --git a/src/widgets/Dashboard.cpp b/src/widgets/Dashboard.cpp index 15b91bbb..781e9015 100644 --- a/src/widgets/Dashboard.cpp +++ b/src/widgets/Dashboard.cpp @@ -21,9 +21,7 @@ #include #include -Dashboard::Dashboard(MainWindow *main) : - CutterDockWidget(main), - ui(new Ui::Dashboard) +Dashboard::Dashboard(MainWindow *main) : CutterDockWidget(main), ui(new Ui::Dashboard) { ui->setupUi(this); @@ -92,7 +90,7 @@ void Dashboard::updateContents() ui->hashesVerticalLayout->addWidget(hashesWidget); // Add hashes as a pair of Hash Name : Hash Value. - for (const QString& key : hashes.keys()) { + for (const QString &key : hashes.keys()) { // Create a bold QString with the hash name uppercased QString label = QString("%1:").arg(key.toUpper()); @@ -164,13 +162,9 @@ void Dashboard::updateContents() ui->verticalLayout_2->addWidget(label); } - - - QSpacerItem *spacer = new QSpacerItem(1, 1, QSizePolicy::Fixed, QSizePolicy::Expanding); ui->verticalLayout_2->addSpacerItem(spacer); - // Get stats for the graphs QStringList stats = Core()->getStats(); @@ -181,7 +175,6 @@ void Dashboard::updateContents() if (Core()->getFileVersionInfo().isEmpty()) { ui->versioninfoButton->setEnabled(false); } - } void Dashboard::on_certificateButton_clicked() diff --git a/src/widgets/Dashboard.h b/src/widgets/Dashboard.h index 67f76162..45e578f6 100644 --- a/src/widgets/Dashboard.h +++ b/src/widgets/Dashboard.h @@ -30,7 +30,7 @@ private slots: void on_versioninfoButton_clicked(); private: - std::unique_ptr ui; + std::unique_ptr ui; void setPlainText(QLineEdit *textBox, const QString &text); void setBool(QLineEdit *textBox, const QJsonObject &jsonObject, const QString &key); diff --git a/src/widgets/DebugActions.cpp b/src/widgets/DebugActions.cpp index 6f09220f..2de927f6 100644 --- a/src/widgets/DebugActions.cpp +++ b/src/widgets/DebugActions.cpp @@ -13,9 +13,7 @@ #include #include -DebugActions::DebugActions(QToolBar *toolBar, MainWindow *main) : - QObject(main), - main(main) +DebugActions::DebugActions(QToolBar *toolBar, MainWindow *main) : QObject(main), main(main) { setObjectName("DebugActions"); // setIconSize(QSize(16, 16)); @@ -101,24 +99,32 @@ DebugActions::DebugActions(QToolBar *toolBar, MainWindow *main) : toolBar->addAction(actionStep); toolBar->addAction(actionStepOut); - allActions = {actionStop, actionAllContinues, actionContinue, actionContinueUntilCall, actionContinueUntilMain, actionContinueUntilSyscall, actionStep, actionStepOut, actionStepOver}; + allActions = { actionStop, + actionAllContinues, + actionContinue, + actionContinueUntilCall, + actionContinueUntilMain, + actionContinueUntilSyscall, + actionStep, + actionStepOut, + actionStepOver }; // hide allactions setAllActionsVisible(false); // Toggle all buttons except restart, suspend(=continue) and stop since those are // necessary to avoid staying stuck - toggleActions = {actionStepOver, actionStep, actionStepOut, actionContinueUntilMain, - actionContinueUntilCall, actionContinueUntilSyscall - }; - toggleConnectionActions = {actionAttach, actionStartRemote}; + toggleActions = { actionStepOver, actionStep, + actionStepOut, actionContinueUntilMain, + actionContinueUntilCall, actionContinueUntilSyscall }; + toggleConnectionActions = { actionAttach, actionStartRemote }; - connect(Core(), &CutterCore::debugProcessFinished, this, [ = ](int pid) { + connect(Core(), &CutterCore::debugProcessFinished, this, [=](int pid) { QMessageBox msgBox; msgBox.setText(tr("Debugged process exited (") + QString::number(pid) + ")"); msgBox.exec(); }); - connect(Core(), &CutterCore::debugTaskStateChanged, this, [ = ]() { + connect(Core(), &CutterCore::debugTaskStateChanged, this, [=]() { bool disableToolbar = Core()->isDebugTaskInProgress(); if (Core()->currentlyDebugging) { for (QAction *a : toggleActions) { @@ -140,7 +146,7 @@ DebugActions::DebugActions(QToolBar *toolBar, MainWindow *main) : }); connect(actionStop, &QAction::triggered, Core(), &CutterCore::stopDebug); - connect(actionStop, &QAction::triggered, [ = ]() { + connect(actionStop, &QAction::triggered, [=]() { actionStart->setVisible(true); actionStartEmul->setVisible(true); actionAttach->setVisible(true); @@ -161,7 +167,7 @@ DebugActions::DebugActions(QToolBar *toolBar, MainWindow *main) : connect(actionStartRemote, &QAction::triggered, this, &DebugActions::attachRemoteDialog); connect(Core(), &CutterCore::attachedRemote, this, &DebugActions::onAttachedRemoteDebugger); connect(actionStartEmul, &QAction::triggered, Core(), &CutterCore::startEmulation); - connect(actionStartEmul, &QAction::triggered, [ = ]() { + connect(actionStartEmul, &QAction::triggered, [=]() { setAllActionsVisible(true); actionStart->setVisible(false); actionAttach->setVisible(false); @@ -177,8 +183,9 @@ DebugActions::DebugActions(QToolBar *toolBar, MainWindow *main) : connect(actionStepOut, &QAction::triggered, Core(), &CutterCore::stepOutDebug); connect(actionContinueUntilMain, &QAction::triggered, this, &DebugActions::continueUntilMain); connect(actionContinueUntilCall, &QAction::triggered, Core(), &CutterCore::continueUntilCall); - connect(actionContinueUntilSyscall, &QAction::triggered, Core(), &CutterCore::continueUntilSyscall); - connect(actionContinue, &QAction::triggered, Core(), [ = ]() { + connect(actionContinueUntilSyscall, &QAction::triggered, Core(), + &CutterCore::continueUntilSyscall); + connect(actionContinue, &QAction::triggered, Core(), [=]() { // Switch between continue and suspend depending on the debugger's state if (Core()->isDebugTaskInProgress()) { Core()->suspendDebug(); @@ -208,8 +215,9 @@ void DebugActions::showDebugWarning() acceptedDebugWarning = true; QMessageBox msgBox; msgBox.setTextInteractionFlags(Qt::TextSelectableByMouse | Qt::LinksAccessibleByMouse); - msgBox.setText(tr("Debug is currently in beta.\n") + - tr("If you encounter any problems or have suggestions, please submit an issue to https://github.com/rizinorg/cutter/issues")); + msgBox.setText(tr("Debug is currently in beta.\n") + + tr("If you encounter any problems or have suggestions, please submit an " + "issue to https://github.com/rizinorg/cutter/issues")); msgBox.exec(); } } @@ -369,9 +377,8 @@ void DebugActions::chooseThemeIcons() { actionContinueUntilSyscall, QStringLiteral("continue_until_syscall.svg") }, }; - // Set the correct icon for the QAction - qhelpers::setThemeIcons(kSupportedIconsNames, [](void *obj, const QIcon & icon) { + qhelpers::setThemeIcons(kSupportedIconsNames, [](void *obj, const QIcon &icon) { static_cast(obj)->setIcon(icon); }); } diff --git a/src/widgets/DebugActions.h b/src/widgets/DebugActions.h index c786b073..4ba280e6 100644 --- a/src/widgets/DebugActions.h +++ b/src/widgets/DebugActions.h @@ -45,7 +45,7 @@ public: // Stop and Detach interchange during runtime QIcon detachIcon; QIcon stopIcon; - + private: /** * @brief buttons that will be disabled/enabled on (disable/enable)DebugToolbar diff --git a/src/widgets/DecompilerWidget.cpp b/src/widgets/DecompilerWidget.cpp index 22098267..e45c8c8a 100644 --- a/src/widgets/DecompilerWidget.cpp +++ b/src/widgets/DecompilerWidget.cpp @@ -20,23 +20,21 @@ #include #include -DecompilerWidget::DecompilerWidget(MainWindow *main) : - MemoryDockWidget(MemoryWidgetType::Decompiler, main), - mCtxMenu(new DecompilerContextMenu(this, main)), - ui(new Ui::DecompilerWidget), - decompilerBusy(false), - seekFromCursor(false), - scrollerHorizontal(0), - scrollerVertical(0), - previousFunctionAddr(RVA_INVALID), - decompiledFunctionAddr(RVA_INVALID), - code(Decompiler::makeWarning(tr("Choose an offset and refresh to get decompiled code")), - &rz_annotated_code_free) +DecompilerWidget::DecompilerWidget(MainWindow *main) + : MemoryDockWidget(MemoryWidgetType::Decompiler, main), + mCtxMenu(new DecompilerContextMenu(this, main)), + ui(new Ui::DecompilerWidget), + decompilerBusy(false), + seekFromCursor(false), + scrollerHorizontal(0), + scrollerVertical(0), + previousFunctionAddr(RVA_INVALID), + decompiledFunctionAddr(RVA_INVALID), + code(Decompiler::makeWarning(tr("Choose an offset and refresh to get decompiled code")), + &rz_annotated_code_free) { ui->setupUi(this); - setObjectName(main - ? main->getUniqueObjectName(getWidgetType()) - : getWidgetType()); + setObjectName(main ? main->getUniqueObjectName(getWidgetType()) : getWidgetType()); updateWindowTitle(); setHighlighter(Config()->isDecompilerAnnotationHighlighterEnabled()); @@ -51,9 +49,7 @@ DecompilerWidget::DecompilerWidget(MainWindow *main) : connect(Core(), &CutterCore::registersChanged, this, &DecompilerWidget::highlightPC); connect(mCtxMenu, &DecompilerContextMenu::copy, this, &DecompilerWidget::copy); - refreshDeferrer = createRefreshDeferrer([this]() { - doRefresh(); - }); + refreshDeferrer = createRefreshDeferrer([this]() { doRefresh(); }); auto decompilers = Core()->getDecompilers(); QString selectedDecompilerId = Config()->getSelectedDecompiler(); @@ -74,13 +70,13 @@ DecompilerWidget::DecompilerWidget(MainWindow *main) : } connect(ui->decompilerComboBox, - static_cast(&QComboBox::currentIndexChanged), this, + static_cast(&QComboBox::currentIndexChanged), this, &DecompilerWidget::decompilerSelected); connectCursorPositionChanged(true); connect(seekable, &CutterSeekable::seekableSeekChanged, this, &DecompilerWidget::seekChanged); ui->textEdit->setContextMenuPolicy(Qt::CustomContextMenu); - connect(ui->textEdit, &QWidget::customContextMenuRequested, - this, &DecompilerWidget::showDecompilerContextMenu); + connect(ui->textEdit, &QWidget::customContextMenuRequested, this, + &DecompilerWidget::showDecompilerContextMenu); connect(Core(), &CutterCore::breakpointsChanged, this, &DecompilerWidget::updateBreakpoints); mCtxMenu->addSeparator(); @@ -124,10 +120,11 @@ ut64 DecompilerWidget::offsetForPosition(size_t pos) size_t closestPos = SIZE_MAX; ut64 closestOffset = mCtxMenu->getFirstOffsetInLine(); void *iter; - rz_vector_foreach(&code->annotations, iter) { + rz_vector_foreach(&code->annotations, iter) + { RzCodeAnnotation *annotation = (RzCodeAnnotation *)iter; if (annotation->type != RZ_CODE_ANNOTATION_TYPE_OFFSET || annotation->start > pos - || annotation->end <= pos) { + || annotation->end <= pos) { continue; } if (closestPos != SIZE_MAX && closestPos >= annotation->start) { @@ -144,9 +141,11 @@ size_t DecompilerWidget::positionForOffset(ut64 offset) size_t closestPos = SIZE_MAX; ut64 closestOffset = UT64_MAX; void *iter; - rz_vector_foreach(&code->annotations, iter) { + rz_vector_foreach(&code->annotations, iter) + { RzCodeAnnotation *annotation = (RzCodeAnnotation *)iter; - if (annotation->type != RZ_CODE_ANNOTATION_TYPE_OFFSET || annotation->offset.offset > offset) { + if (annotation->type != RZ_CODE_ANNOTATION_TYPE_OFFSET + || annotation->offset.offset > offset) { continue; } if (closestOffset != UT64_MAX && closestOffset >= annotation->offset.offset) { @@ -193,14 +192,16 @@ void DecompilerWidget::gatherBreakpointInfo(RzAnnotatedCode &codeDecompiled, siz { RVA firstOffset = RVA_MAX; void *iter; - rz_vector_foreach(&codeDecompiled.annotations, iter) { + rz_vector_foreach(&codeDecompiled.annotations, iter) + { RzCodeAnnotation *annotation = (RzCodeAnnotation *)iter; if (annotation->type != RZ_CODE_ANNOTATION_TYPE_OFFSET) { continue; } - if ((startPos <= annotation->start && annotation->start < endPos) || (startPos < annotation->end - && annotation->end < endPos)) { - firstOffset = (annotation->offset.offset < firstOffset) ? annotation->offset.offset : firstOffset; + if ((startPos <= annotation->start && annotation->start < endPos) + || (startPos < annotation->end && annotation->end < endPos)) { + firstOffset = (annotation->offset.offset < firstOffset) ? annotation->offset.offset + : firstOffset; } } mCtxMenu->setFirstOffsetInLine(firstOffset); @@ -236,7 +237,8 @@ void DecompilerWidget::doRefresh() if (!dec) { return; } - // Disabling decompiler selection combo box and making progress label visible ahead of decompilation. + // Disabling decompiler selection combo box and making progress label visible ahead of + // decompilation. ui->progressLabel->setVisible(true); ui->decompilerComboBox->setEnabled(false); if (dec->isRunning()) { @@ -257,8 +259,8 @@ void DecompilerWidget::doRefresh() ui->progressLabel->setVisible(false); ui->decompilerComboBox->setEnabled(true); setCode(Decompiler::makeWarning( - tr("No function found at this offset. " - "Seek to a function or define one in order to decompile it."))); + tr("No function found at this offset. " + "Seek to a function or define one in order to decompile it."))); return; } mCtxMenu->setDecompiledFunctionAddress(decompiledFunctionAddr); @@ -315,7 +317,8 @@ void DecompilerWidget::decompilationFinished(RzAnnotatedCode *codeDecompiled) lowestOffsetInCode = RVA_MAX; highestOffsetInCode = 0; void *iter; - rz_vector_foreach(&code->annotations, iter) { + rz_vector_foreach(&code->annotations, iter) + { RzCodeAnnotation *annotation = (RzCodeAnnotation *)iter; if (annotation->type == RZ_CODE_ANNOTATION_TYPE_OFFSET) { if (lowestOffsetInCode > annotation->offset.offset) { @@ -338,11 +341,12 @@ void DecompilerWidget::setAnnotationsAtCursor(size_t pos) { RzCodeAnnotation *annotationAtPos = nullptr; void *iter; - rz_vector_foreach(&this->code->annotations, iter) { + rz_vector_foreach(&this->code->annotations, iter) + { RzCodeAnnotation *annotation = (RzCodeAnnotation *)iter; - if (annotation->type == RZ_CODE_ANNOTATION_TYPE_OFFSET || - annotation->type == RZ_CODE_ANNOTATION_TYPE_SYNTAX_HIGHLIGHT || - annotation->start > pos || annotation->end <= pos) { + if (annotation->type == RZ_CODE_ANNOTATION_TYPE_OFFSET + || annotation->type == RZ_CODE_ANNOTATION_TYPE_SYNTAX_HIGHLIGHT + || annotation->start > pos || annotation->end <= pos) { continue; } annotationAtPos = annotation; @@ -482,14 +486,14 @@ void DecompilerWidget::seekToReference() bool DecompilerWidget::eventFilter(QObject *obj, QEvent *event) { if (event->type() == QEvent::MouseButtonDblClick - && (obj == ui->textEdit || obj == ui->textEdit->viewport())) { + && (obj == ui->textEdit || obj == ui->textEdit->viewport())) { QMouseEvent *mouseEvent = static_cast(event); ui->textEdit->setTextCursor(ui->textEdit->cursorForPosition(mouseEvent->pos())); seekToReference(); return true; } if (event->type() == QEvent::MouseButtonPress - && (obj == ui->textEdit || obj == ui->textEdit->viewport())) { + && (obj == ui->textEdit || obj == ui->textEdit->viewport())) { QMouseEvent *mouseEvent = static_cast(event); if (mouseEvent->button() == Qt::RightButton && !ui->textEdit->textCursor().hasSelection()) { ui->textEdit->setTextCursor(ui->textEdit->cursorForPosition(mouseEvent->pos())); @@ -502,7 +506,8 @@ bool DecompilerWidget::eventFilter(QObject *obj, QEvent *event) void DecompilerWidget::highlightPC() { RVA PCAddress = Core()->getProgramCounterValue(); - if (PCAddress == RVA_INVALID || (Core()->getFunctionStart(PCAddress) != decompiledFunctionAddr)) { + if (PCAddress == RVA_INVALID + || (Core()->getFunctionStart(PCAddress) != decompiledFunctionAddr)) { return; } @@ -510,7 +515,6 @@ void DecompilerWidget::highlightPC() if (!cursor.isNull()) { colorLine(createLineHighlightPC(cursor)); } - } void DecompilerWidget::highlightBreakpoints() @@ -520,11 +524,13 @@ void DecompilerWidget::highlightBreakpoints() QTextCursor cursor; for (RVA &bp : functionBreakpoints) { if (bp == RVA_INVALID) { - continue;; + continue; + ; } cursor = getCursorForAddress(bp); if (!cursor.isNull()) { - // Use a Block formatting since these lines are not updated frequently as selections and PC + // Use a Block formatting since these lines are not updated frequently as selections and + // PC QTextBlockFormat f; f.setBackground(ConfigColor("gui.breakpoint_background")); cursor.setBlockFormat(f); @@ -566,8 +572,8 @@ bool DecompilerWidget::addressInRange(RVA addr) } /** - * Convert annotation ranges from byte offsets in utf8 used by RzAnnotated code to QString QChars used by QString - * and Qt text editor. + * Convert annotation ranges from byte offsets in utf8 used by RzAnnotated code to QString QChars + * used by QString and Qt text editor. * @param code - RzAnnotated code with annotations that need to be modified * @return Decompiled code */ @@ -592,7 +598,8 @@ static QString remapAnnotationOffsetsToQString(RzAnnotatedCode &code) }; void *iter; - rz_vector_foreach(&code.annotations, iter) { + rz_vector_foreach(&code.annotations, iter) + { RzCodeAnnotation *annotation = (RzCodeAnnotation *)iter; annotation->start = mapPos(annotation->start); annotation->end = mapPos(annotation->end); @@ -603,7 +610,7 @@ static QString remapAnnotationOffsetsToQString(RzAnnotatedCode &code) void DecompilerWidget::setCode(RzAnnotatedCode *code) { connectCursorPositionChanged(false); - if (auto highlighter = qobject_cast(syntaxHighlighter.get())) { + if (auto highlighter = qobject_cast(syntaxHighlighter.get())) { highlighter->setAnnotations(code); } this->code.reset(code); @@ -618,7 +625,7 @@ void DecompilerWidget::setHighlighter(bool annotationBasedHighlighter) usingAnnotationBasedHighlighting = annotationBasedHighlighter; if (usingAnnotationBasedHighlighting) { syntaxHighlighter.reset(new DecompilerHighlighter()); - static_cast(syntaxHighlighter.get())->setAnnotations(code.get()); + static_cast(syntaxHighlighter.get())->setAnnotations(code.get()); } else { syntaxHighlighter.reset(Config()->createSyntaxHighlighter(nullptr)); } diff --git a/src/widgets/DecompilerWidget.h b/src/widgets/DecompilerWidget.h index 79799ad1..22d0abf7 100644 --- a/src/widgets/DecompilerWidget.h +++ b/src/widgets/DecompilerWidget.h @@ -66,8 +66,8 @@ private: bool decompilerSelectionEnabled; /** - * True if the selected decompiler is currently running a decompilation for this widget. Once the decompilation - * is over, this should be set to false. + * True if the selected decompiler is currently running a decompilation for this widget. Once + * the decompilation is over, this should be set to false. */ bool decompilerBusy; @@ -79,11 +79,13 @@ private: std::unique_ptr code; /** - * Specifies the lowest offset of instructions among all the instructions in the decompiled function. + * Specifies the lowest offset of instructions among all the instructions in the decompiled + * function. */ RVA lowestOffsetInCode; /** - * Specifies the highest offset of instructions among all the instructions in the decompiled function. + * Specifies the highest offset of instructions among all the instructions in the decompiled + * function. */ RVA highestOffsetInCode; @@ -95,7 +97,8 @@ private: Decompiler *getCurrentDecompiler(); /** - * @brief Calls the function doRefresh() if the address specified is a part of the decompiled function. + * @brief Calls the function doRefresh() if the address specified is a part of the decompiled + * function. * * @param addr Address at which a change occurred. */ @@ -177,19 +180,20 @@ private: bool colorLine(QTextEdit::ExtraSelection extraSelection); /** - * @brief This function is responsible for highlighting all the breakpoints in the decompiler view. - * It will also run when a breakpoint is added, removed or modified. + * @brief This function is responsible for highlighting all the breakpoints in the decompiler + * view. It will also run when a breakpoint is added, removed or modified. */ void highlightBreakpoints(); /** - * @brief Finds the earliest offset and breakpoints within the specified range [startPos, endPos] - * in the specified RzAnnotatedCode. + * @brief Finds the earliest offset and breakpoints within the specified range [startPos, + * endPos] in the specified RzAnnotatedCode. * - * This function is supposed to be used for finding the earliest offset and breakpoints within the specified range - * [startPos, endPos]. This will set the value of the variables 'RVA firstOffsetInLine' and 'QVector availableBreakpoints' in - * the context menu. + * This function is supposed to be used for finding the earliest offset and breakpoints within + * the specified range [startPos, endPos]. This will set the value of the variables 'RVA + * firstOffsetInLine' and 'QVector availableBreakpoints' in the context menu. * - * @param codeDecompiled - A reference to the RzAnnotatedCode for the function that is decompiled. + * @param codeDecompiled - A reference to the RzAnnotatedCode for the function that is + * decompiled. * @param startPos - Position of the start of the range(inclusive). * @param endPos - Position of the end of the range(inclusive). */ @@ -197,8 +201,8 @@ private: /** * @brief Finds the offset that's closest to the specified position in the decompiled code. * - * @note If no annotations that covers the specified position is found, the first offset in the line - * containing specified position will be returned + * @note If no annotations that covers the specified position is found, the first offset in the + * line containing specified position will be returned * * @param pos - Position of the decompiled code. * @return Offset for the specified position/first offset in line. diff --git a/src/widgets/DisassemblerGraphView.cpp b/src/widgets/DisassemblerGraphView.cpp index 9c40a601..b339c1bc 100644 --- a/src/widgets/DisassemblerGraphView.cpp +++ b/src/widgets/DisassemblerGraphView.cpp @@ -30,7 +30,8 @@ #include DisassemblerGraphView::DisassemblerGraphView(QWidget *parent, CutterSeekable *seekable, - MainWindow *mainWindow, QList additionalMenuActions) + MainWindow *mainWindow, + QList additionalMenuActions) : CutterGraphView(parent), blockMenu(new DisassemblyContextMenu(this, mainWindow)), contextMenu(new QMenu(this)), @@ -84,7 +85,6 @@ DisassemblerGraphView::DisassemblerGraphView(QWidget *parent, CutterSeekable *se contextMenu->addSeparator(); contextMenu->addActions(additionalMenuActions); - QAction *highlightBB = new QAction(this); actionUnhighlight.setVisible(false); @@ -129,7 +129,6 @@ DisassemblerGraphView::DisassemblerGraphView(QWidget *parent, CutterSeekable *se blockMenu->addAction(highlightBI); blockMenu->addAction(&actionUnhighlightInstruction); - // Include all actions from generic context menu in block specific menu blockMenu->addSeparator(); blockMenu->addActions(contextMenu->actions()); @@ -172,9 +171,9 @@ void DisassemblerGraphView::loadCurrentGraph() { TempConfig tempConfig; tempConfig.set("scr.color", COLOR_MODE_16M) - .set("asm.bb.line", false) - .set("asm.lines", false) - .set("asm.lines.fcn", false); + .set("asm.bb.line", false) + .set("asm.lines", false) + .set("asm.lines.fcn", false); QJsonArray functions; RzAnalysisFunction *fcn = Core()->functionIn(seekable->getOffset()); @@ -275,7 +274,8 @@ void DisassemblerGraphView::loadCurrentGraph() if (opIndex < opArray.size() - 1) { // get instruction size from distance to next instruction ... - RVA nextOffset = opArray[opIndex + 1].toObject()["offset"].toVariant().toULongLong(); + RVA nextOffset = + opArray[opIndex + 1].toObject()["offset"].toVariant().toULongLong(); i.size = nextOffset - i.addr; } else { // or to the end of the block. @@ -288,11 +288,11 @@ void DisassemblerGraphView::loadCurrentGraph() i.plainText = textDoc.toPlainText(); RichTextPainter::List richText = RichTextPainter::fromTextDocument(textDoc); - //Colors::colorizeAssembly(richText, textDoc.toPlainText(), 0); + // Colors::colorizeAssembly(richText, textDoc.toPlainText(), 0); bool cropped; - int blockLength = Config()->getGraphBlockMaxChars() + Core()->getConfigb("asm.bytes") * 24 + - Core()->getConfigb("asm.emu") * 10; + int blockLength = Config()->getGraphBlockMaxChars() + + Core()->getConfigb("asm.bytes") * 24 + Core()->getConfigb("asm.emu") * 10; i.text = Text(RichTextPainter::cropped(richText, blockLength, "...", &cropped)); if (cropped) i.fullText = richText; @@ -317,7 +317,8 @@ DisassemblerGraphView::EdgeConfigurationMapping DisassemblerGraphView::getEdgeCo EdgeConfigurationMapping result; for (auto &block : blocks) { for (const auto &edge : block.second.edges) { - result[ {block.first, edge.target}] = edgeConfiguration(block.second, &blocks[edge.target], false); + result[{ block.first, edge.target }] = + edgeConfiguration(block.second, &blocks[edge.target], false); } } return result; @@ -429,7 +430,8 @@ void DisassemblerGraphView::drawBlock(QPainter &p, GraphView::GraphBlock &block, int tokenEnd = pos + highlight_token->content.length(); if ((pos > 0 && instr.plainText[pos - 1].isLetterOrNumber()) - || (tokenEnd < instr.plainText.length() && instr.plainText[tokenEnd].isLetterOrNumber())) { + || (tokenEnd < instr.plainText.length() + && instr.plainText[tokenEnd].isLetterOrNumber())) { continue; } @@ -446,7 +448,8 @@ void DisassemblerGraphView::drawBlock(QPainter &p, GraphView::GraphBlock &block, QColor selectionColor = ConfigColor("wordHighlight"); p.fillRect(QRectF(block.x + charWidth * 3 + widthBefore, y, highlightWidth, - charHeight), selectionColor); + charHeight), + selectionColor); } y += int(instr.text.lines.size()) * charHeight; @@ -492,14 +495,13 @@ void DisassemblerGraphView::drawBlock(QPainter &p, GraphView::GraphBlock &block, } // Assume charWidth <= charHeight // TODO: Breakpoint/Cip stuff - QRectF bpRect(x - rectSize / 3.0, y + (charHeight - rectSize) / 2.0, rectSize, rectSize); + QRectF bpRect(x - rectSize / 3.0, y + (charHeight - rectSize) / 2.0, rectSize, + rectSize); Q_UNUSED(bpRect); - RichTextPainter::paintRichText(&p, x + charWidth, y, - block.width - charWidth, charHeight, 0, line, - mFontMetrics.get()); + RichTextPainter::paintRichText(&p, x + charWidth, y, block.width - charWidth, + charHeight, 0, line, mFontMetrics.get()); y += charHeight; - } } } @@ -529,7 +531,6 @@ GraphView::EdgeConfiguration DisassemblerGraphView::edgeConfiguration(GraphView: return ec; } - RVA DisassemblerGraphView::getAddrForMouseEvent(GraphBlock &block, QPoint *point) { DisassemblyBlock &db = disassembly_blocks[block.entry]; @@ -554,8 +555,9 @@ RVA DisassemblerGraphView::getAddrForMouseEvent(GraphBlock &block, QPoint *point return RVA_INVALID; } -DisassemblerGraphView::Instr *DisassemblerGraphView::getInstrForMouseEvent( - GraphView::GraphBlock &block, QPoint *point, bool force) +DisassemblerGraphView::Instr * +DisassemblerGraphView::getInstrForMouseEvent(GraphView::GraphBlock &block, QPoint *point, + bool force) { DisassemblyBlock &db = disassembly_blocks[block.entry]; @@ -570,7 +572,7 @@ DisassemblerGraphView::Instr *DisassemblerGraphView::getInstrForMouseEvent( int cur_row = 0; for (Instr &instr : db.instrs) { - if (mouse_row < cur_row + (int) instr.text.lines.size()) { + if (mouse_row < cur_row + (int)instr.text.lines.size()) { return &instr; } cur_row += instr.text.lines.size(); @@ -612,8 +614,9 @@ QRectF DisassemblerGraphView::getInstrRect(GraphView::GraphBlock &block, RVA add i++; } QPointF topLeft = getInstructionOffset(db, static_cast(firstLineWithAddr)); - return QRectF(topLeft, QSizeF(block.width - 4 * charWidth, - charHeight * int(currentLine - firstLineWithAddr))); + return QRectF(topLeft, + QSizeF(block.width - 4 * charWidth, + charHeight * int(currentLine - firstLineWithAddr))); } currentLine += instr.text.lines.size(); } @@ -678,7 +681,6 @@ void DisassemblerGraphView::onSeekChanged(RVA addr) } } - void DisassemblerGraphView::takeTrue() { DisassemblyBlock *db = blockForAddress(seekable->getOffset()); @@ -760,7 +762,8 @@ void DisassemblerGraphView::seekLocal(RVA addr, bool update_viewport) void DisassemblerGraphView::copySelection() { - if (!highlight_token) return; + if (!highlight_token) + return; QClipboard *clipboard = QApplication::clipboard(); clipboard->setText(highlight_token->content); @@ -768,7 +771,7 @@ void DisassemblerGraphView::copySelection() DisassemblerGraphView::Token *DisassemblerGraphView::getToken(Instr *instr, int x) { - x -= (int) (3 * charWidth); // Ignore left margin + x -= (int)(3 * charWidth); // Ignore left margin if (x < 0) { return nullptr; } @@ -831,7 +834,8 @@ void DisassemblerGraphView::blockContextMenuRequested(GraphView::GraphBlock &blo { const RVA offset = this->seekable->getOffset(); actionUnhighlight.setVisible(Core()->getBBHighlighter()->getBasicBlock(block.entry)); - actionUnhighlightInstruction.setVisible(Core()->getBIHighlighter()->getBasicInstruction(offset)); + actionUnhighlightInstruction.setVisible( + Core()->getBIHighlighter()->getBasicInstruction(offset)); event->accept(); blockMenu->exec(event->globalPos()); } @@ -840,7 +844,7 @@ void DisassemblerGraphView::contextMenuEvent(QContextMenuEvent *event) { GraphView::contextMenuEvent(event); if (!event->isAccepted()) { - //TODO: handle opening block menu using keyboard + // TODO: handle opening block menu using keyboard contextMenu->exec(event->globalPos()); event->accept(); } @@ -901,7 +905,6 @@ void DisassemblerGraphView::blockTransitionedTo(GraphView::GraphBlock *to) seekLocal(to->entry); } - void DisassemblerGraphView::onActionHighlightBITriggered() { const RVA offset = this->seekable->getOffset(); @@ -917,8 +920,8 @@ void DisassemblerGraphView::onActionHighlightBITriggered() background = currentColor->color; } - QColor c = QColorDialog::getColor(background, this, QString(), - QColorDialog::DontUseNativeDialog); + QColor c = + QColorDialog::getColor(background, this, QString(), QColorDialog::DontUseNativeDialog); if (c.isValid()) { bih->highlight(instr->addr, instr->size, c); } @@ -944,7 +947,6 @@ void DisassemblerGraphView::restoreCurrentBlock() onSeekChanged(this->seekable->getOffset()); // try to keep the view on current block } - void DisassemblerGraphView::paintEvent(QPaintEvent *event) { // DisassemblerGraphView is always dirty diff --git a/src/widgets/DisassemblerGraphView.h b/src/widgets/DisassemblerGraphView.h index 3f8697c2..beb2b209 100644 --- a/src/widgets/DisassemblerGraphView.h +++ b/src/widgets/DisassemblerGraphView.h @@ -20,7 +20,8 @@ class DisassemblerGraphView : public CutterGraphView { Q_OBJECT - struct Text { + struct Text + { std::vector lines; Text() {} @@ -33,15 +34,13 @@ class DisassemblerGraphView : public CutterGraphView rt.text = text; rt.textColor = color; rt.textBackground = background; - rt.flags = rt.textBackground.alpha() ? RichTextPainter::FlagAll : RichTextPainter::FlagColor; + rt.flags = rt.textBackground.alpha() ? RichTextPainter::FlagAll + : RichTextPainter::FlagColor; richText.push_back(rt); lines.push_back(richText); } - Text(const RichTextPainter::List &richText) - { - lines.push_back(richText); - } + Text(const RichTextPainter::List &richText) { lines.push_back(richText); } QString ToQString() const { @@ -55,19 +54,21 @@ class DisassemblerGraphView : public CutterGraphView } }; - struct Instr { + struct Instr + { ut64 addr = 0; ut64 size = 0; Text text; Text fullText; QString plainText; - std::vector opcode; //instruction bytes + std::vector opcode; // instruction bytes bool empty() const { return size == 0; } bool contains(ut64 addr) const; }; - struct Token { + struct Token + { int start; int length; QString type; @@ -76,7 +77,8 @@ class DisassemblerGraphView : public CutterGraphView QString content; }; - struct DisassemblyBlock { + struct DisassemblyBlock + { Text header_text; std::vector instrs; ut64 entry = 0; @@ -92,11 +94,13 @@ public: ~DisassemblerGraphView() override; std::unordered_map disassembly_blocks; virtual void drawBlock(QPainter &p, GraphView::GraphBlock &block, bool interactive) override; - virtual void blockClicked(GraphView::GraphBlock &block, QMouseEvent *event, QPoint pos) override; + virtual void blockClicked(GraphView::GraphBlock &block, QMouseEvent *event, + QPoint pos) override; virtual void blockDoubleClicked(GraphView::GraphBlock &block, QMouseEvent *event, QPoint pos) override; virtual bool helpEvent(QHelpEvent *event) override; - virtual void blockHelpEvent(GraphView::GraphBlock &block, QHelpEvent *event, QPoint pos) override; + virtual void blockHelpEvent(GraphView::GraphBlock &block, QHelpEvent *event, + QPoint pos) override; virtual GraphView::EdgeConfiguration edgeConfiguration(GraphView::GraphBlock &from, GraphView::GraphBlock *to, bool interactive) override; @@ -185,7 +189,7 @@ signals: void nameChanged(const QString &name); public: - bool isGraphEmpty() { return emptyGraph; } + bool isGraphEmpty() { return emptyGraph; } }; #endif // DISASSEMBLERGRAPHVIEW_H diff --git a/src/widgets/DisassemblyWidget.cpp b/src/widgets/DisassemblyWidget.cpp index 2116d4d6..32ef79dc 100644 --- a/src/widgets/DisassemblyWidget.cpp +++ b/src/widgets/DisassemblyWidget.cpp @@ -18,16 +18,12 @@ #include #include - -class DisassemblyTextBlockUserData: public QTextBlockUserData +class DisassemblyTextBlockUserData : public QTextBlockUserData { public: DisassemblyLine line; - explicit DisassemblyTextBlockUserData(const DisassemblyLine &line) - { - this->line = line; - } + explicit DisassemblyTextBlockUserData(const DisassemblyLine &line) { this->line = line; } }; static DisassemblyTextBlockUserData *getUserData(const QTextBlock &block) @@ -41,14 +37,12 @@ static DisassemblyTextBlockUserData *getUserData(const QTextBlock &block) } DisassemblyWidget::DisassemblyWidget(MainWindow *main) - : MemoryDockWidget(MemoryWidgetType::Disassembly, main) - , mCtxMenu(new DisassemblyContextMenu(this, main)) - , mDisasScrollArea(new DisassemblyScrollArea(this)) - , mDisasTextEdit(new DisassemblyTextEdit(this)) + : MemoryDockWidget(MemoryWidgetType::Disassembly, main), + mCtxMenu(new DisassemblyContextMenu(this, main)), + mDisasScrollArea(new DisassemblyScrollArea(this)), + mDisasTextEdit(new DisassemblyTextEdit(this)) { - setObjectName(main - ? main->getUniqueObjectName(getWidgetType()) - : getWidgetType()); + setObjectName(main ? main->getUniqueObjectName(getWidgetType()) : getWidgetType()); updateWindowTitle(); topOffset = bottomOffset = RVA_INVALID; @@ -82,15 +76,14 @@ DisassemblyWidget::DisassemblyWidget(MainWindow *main) setFocusPolicy(Qt::ClickFocus); // Behave like all widgets: highlight on focus and hover - connect(qApp, &QApplication::focusChanged, this, [this](QWidget* , QWidget* now) { - QColor borderColor = this == now - ? palette().color(QPalette::Highlight) - : palette().color(QPalette::WindowText).darker(); + connect(qApp, &QApplication::focusChanged, this, [this](QWidget *, QWidget *now) { + QColor borderColor = this == now ? palette().color(QPalette::Highlight) + : palette().color(QPalette::WindowText).darker(); widget()->setStyleSheet(QString("QSplitter { border: %1px solid %2 } \n" "QSplitter:hover { border: %1px solid %3 } \n") - .arg(devicePixelRatio()) - .arg(borderColor.name()) - .arg(palette().color(QPalette::Highlight).name())); + .arg(devicePixelRatio()) + .arg(borderColor.name()) + .arg(palette().color(QPalette::Highlight).name())); }); splitter->setFrameShape(QFrame::Box); @@ -108,9 +101,8 @@ DisassemblyWidget::DisassemblyWidget(MainWindow *main) setupFonts(); setupColors(); - disasmRefresh = createReplacingRefreshDeferrer(false, [this](const RVA *offset) { - refreshDisasm(offset ? *offset : RVA_INVALID); - }); + disasmRefresh = createReplacingRefreshDeferrer( + false, [this](const RVA *offset) { refreshDisasm(offset ? *offset : RVA_INVALID); }); maxLines = 0; updateMaxLines(); @@ -132,24 +124,25 @@ DisassemblyWidget::DisassemblyWidget(MainWindow *main) // Set Disas context menu mDisasTextEdit->setContextMenuPolicy(Qt::CustomContextMenu); - connect(mDisasTextEdit, &QWidget::customContextMenuRequested, - this, &DisassemblyWidget::showDisasContextMenu); + connect(mDisasTextEdit, &QWidget::customContextMenuRequested, this, + &DisassemblyWidget::showDisasContextMenu); - - connect(mDisasScrollArea, &DisassemblyScrollArea::scrollLines, this, &DisassemblyWidget::scrollInstructions); - connect(mDisasScrollArea, &DisassemblyScrollArea::disassemblyResized, this, &DisassemblyWidget::updateMaxLines); + connect(mDisasScrollArea, &DisassemblyScrollArea::scrollLines, this, + &DisassemblyWidget::scrollInstructions); + connect(mDisasScrollArea, &DisassemblyScrollArea::disassemblyResized, this, + &DisassemblyWidget::updateMaxLines); connectCursorPositionChanged(false); - connect(mDisasTextEdit->verticalScrollBar(), &QScrollBar::valueChanged, this, [ = ](int value) { + connect(mDisasTextEdit->verticalScrollBar(), &QScrollBar::valueChanged, this, [=](int value) { if (value != 0) { mDisasTextEdit->verticalScrollBar()->setValue(0); } }); - connect(Core(), &CutterCore::commentsChanged, this, [this]() {refreshDisasm();}); + connect(Core(), &CutterCore::commentsChanged, this, [this]() { refreshDisasm(); }); connect(Core(), SIGNAL(flagsChanged()), this, SLOT(refreshDisasm())); connect(Core(), SIGNAL(functionsChanged()), this, SLOT(refreshDisasm())); - connect(Core(), &CutterCore::functionRenamed, this, [this]() {refreshDisasm();}); + connect(Core(), &CutterCore::functionRenamed, this, [this]() { refreshDisasm(); }); connect(Core(), SIGNAL(varsChanged()), this, SLOT(refreshDisasm())); connect(Core(), SIGNAL(asmOptionsChanged()), this, SLOT(refreshDisasm())); connect(Core(), &CutterCore::instructionChanged, this, &DisassemblyWidget::refreshIfInRange); @@ -159,66 +152,58 @@ DisassemblyWidget::DisassemblyWidget(MainWindow *main) connect(Config(), &Configuration::fontsUpdated, this, &DisassemblyWidget::fontsUpdatedSlot); connect(Config(), &Configuration::colorsUpdated, this, &DisassemblyWidget::colorsUpdatedSlot); - connect(Core(), &CutterCore::refreshAll, this, [this]() { - refreshDisasm(seekable->getOffset()); - }); + connect(Core(), &CutterCore::refreshAll, this, + [this]() { refreshDisasm(seekable->getOffset()); }); refreshDisasm(seekable->getOffset()); connect(mCtxMenu, &DisassemblyContextMenu::copy, mDisasTextEdit, &QPlainTextEdit::copy); mCtxMenu->addSeparator(); mCtxMenu->addAction(&syncAction); - connect(seekable, &CutterSeekable::seekableSeekChanged, this, &DisassemblyWidget::on_seekChanged); + connect(seekable, &CutterSeekable::seekableSeekChanged, this, + &DisassemblyWidget::on_seekChanged); addActions(mCtxMenu->actions()); -#define ADD_ACTION(ksq, ctx, slot) {\ - QAction *a = new QAction(this); \ - a->setShortcut(ksq); \ - a->setShortcutContext(ctx); \ - addAction(a); \ - connect(a, &QAction::triggered, this, (slot)); } +#define ADD_ACTION(ksq, ctx, slot) \ + { \ + QAction *a = new QAction(this); \ + a->setShortcut(ksq); \ + a->setShortcutContext(ctx); \ + addAction(a); \ + connect(a, &QAction::triggered, this, (slot)); \ + } // Space to switch to graph - ADD_ACTION(Qt::Key_Space, Qt::WidgetWithChildrenShortcut, [this] { - mainWindow->showMemoryWidget(MemoryWidgetType::Graph); - }) + ADD_ACTION(Qt::Key_Space, Qt::WidgetWithChildrenShortcut, + [this] { mainWindow->showMemoryWidget(MemoryWidgetType::Graph); }) ADD_ACTION(Qt::Key_Escape, Qt::WidgetWithChildrenShortcut, &DisassemblyWidget::seekPrev) - ADD_ACTION(Qt::Key_J, Qt::WidgetWithChildrenShortcut, [this]() { - moveCursorRelative(false, false); - }) - ADD_ACTION(QKeySequence::MoveToNextLine, Qt::WidgetWithChildrenShortcut, [this]() { - moveCursorRelative(false, false); - }) - ADD_ACTION(Qt::Key_K, Qt::WidgetWithChildrenShortcut, [this]() { - moveCursorRelative(true, false); - }) - ADD_ACTION(QKeySequence::MoveToPreviousLine, Qt::WidgetWithChildrenShortcut, [this]() { - moveCursorRelative(true, false); - }) - ADD_ACTION(QKeySequence::MoveToNextPage, Qt::WidgetWithChildrenShortcut, [this]() { - moveCursorRelative(false, true); - }) - ADD_ACTION(QKeySequence::MoveToPreviousPage, Qt::WidgetWithChildrenShortcut, [this]() { - moveCursorRelative(true, true); - }) + ADD_ACTION(Qt::Key_J, Qt::WidgetWithChildrenShortcut, + [this]() { moveCursorRelative(false, false); }) + ADD_ACTION(QKeySequence::MoveToNextLine, Qt::WidgetWithChildrenShortcut, + [this]() { moveCursorRelative(false, false); }) + ADD_ACTION(Qt::Key_K, Qt::WidgetWithChildrenShortcut, + [this]() { moveCursorRelative(true, false); }) + ADD_ACTION(QKeySequence::MoveToPreviousLine, Qt::WidgetWithChildrenShortcut, + [this]() { moveCursorRelative(true, false); }) + ADD_ACTION(QKeySequence::MoveToNextPage, Qt::WidgetWithChildrenShortcut, + [this]() { moveCursorRelative(false, true); }) + ADD_ACTION(QKeySequence::MoveToPreviousPage, Qt::WidgetWithChildrenShortcut, + [this]() { moveCursorRelative(true, true); }) #undef ADD_ACTION } void DisassemblyWidget::setPreviewMode(bool previewMode) { - mDisasTextEdit->setContextMenuPolicy(previewMode - ? Qt::NoContextMenu - : Qt::CustomContextMenu); + mDisasTextEdit->setContextMenuPolicy(previewMode ? Qt::NoContextMenu : Qt::CustomContextMenu); mCtxMenu->setEnabled(!previewMode); for (auto action : mCtxMenu->actions()) { action->setEnabled(!previewMode); } for (auto action : actions()) { - if (action->shortcut() == Qt::Key_Space || - action->shortcut() == Qt::Key_Escape) { + if (action->shortcut() == Qt::Key_Space || action->shortcut() == Qt::Key_Escape) { action->setEnabled(!previewMode); } } @@ -256,7 +241,7 @@ void DisassemblyWidget::refreshIfInRange(RVA offset) void DisassemblyWidget::refreshDisasm(RVA offset) { - if(!disasmRefresh->attemptRefresh(offset == RVA_INVALID ? nullptr : new RVA(offset))) { + if (!disasmRefresh->attemptRefresh(offset == RVA_INVALID ? nullptr : new RVA(offset))) { return; } @@ -282,8 +267,7 @@ void DisassemblyWidget::refreshDisasm(RVA offset) // Retrieve disassembly lines { TempConfig tempConfig; - tempConfig.set("scr.color", COLOR_MODE_16M) - .set("asm.lines", false); + tempConfig.set("scr.color", COLOR_MODE_16M).set("asm.lines", false); lines = Core()->disassembleLines(topOffset, maxLines); } @@ -336,7 +320,6 @@ void DisassemblyWidget::refreshDisasm(RVA offset) leftPanel->update(); } - void DisassemblyWidget::scrollInstructions(int count) { if (count == 0) { @@ -359,7 +342,6 @@ void DisassemblyWidget::scrollInstructions(int count) refreshDisasm(offset); } - bool DisassemblyWidget::updateMaxLines() { int currentMaxLines = qhelpers::getMaxFullyDisplayedLines(mDisasTextEdit); @@ -497,7 +479,8 @@ void DisassemblyWidget::updateCursorPosition() if (offset < topOffset || (offset > bottomOffset && bottomOffset != RVA_INVALID)) { mDisasTextEdit->moveCursor(QTextCursor::Start); - mDisasTextEdit->setExtraSelections(createSameWordsSelections(mDisasTextEdit, curHighlightedWord)); + mDisasTextEdit->setExtraSelections( + createSameWordsSelections(mDisasTextEdit, curHighlightedWord)); } else { RVA currentCursorOffset = readCurrentDisassemblyOffset(); QTextCursor originalCursor = mDisasTextEdit->textCursor(); @@ -509,11 +492,13 @@ void DisassemblyWidget::updateCursorPosition() RVA lineOffset = readDisassemblyOffset(cursor); if (lineOffset == offset) { if (cursorLineOffset > 0) { - cursor.movePosition(QTextCursor::Down, QTextCursor::MoveAnchor, cursorLineOffset); + cursor.movePosition(QTextCursor::Down, QTextCursor::MoveAnchor, + cursorLineOffset); } if (cursorCharOffset > 0) { cursor.movePosition(QTextCursor::StartOfLine); - cursor.movePosition(QTextCursor::Right, QTextCursor::MoveAnchor, cursorCharOffset); + cursor.movePosition(QTextCursor::Right, QTextCursor::MoveAnchor, + cursorCharOffset); } mDisasTextEdit->setTextCursor(cursor); @@ -548,10 +533,11 @@ void DisassemblyWidget::updateCursorPosition() void DisassemblyWidget::connectCursorPositionChanged(bool disconnect) { if (disconnect) { - QObject::disconnect(mDisasTextEdit, &QPlainTextEdit::cursorPositionChanged, - this, &DisassemblyWidget::cursorPositionChanged); + QObject::disconnect(mDisasTextEdit, &QPlainTextEdit::cursorPositionChanged, this, + &DisassemblyWidget::cursorPositionChanged); } else { - connect(mDisasTextEdit, &QPlainTextEdit::cursorPositionChanged, this, &DisassemblyWidget::cursorPositionChanged); + connect(mDisasTextEdit, &QPlainTextEdit::cursorPositionChanged, this, + &DisassemblyWidget::cursorPositionChanged); } } @@ -614,7 +600,7 @@ void DisassemblyWidget::moveCursorRelative(bool up, bool page) int overflowLines = oldTopLine - maxLines; if (overflowLines > 0) { while (lines[overflowLines - 1].offset == lines[overflowLines].offset - && overflowLines < lines.length() - 1) { + && overflowLines < lines.length() - 1) { overflowLines++; } offset = lines[overflowLines].offset; @@ -660,13 +646,13 @@ bool DisassemblyWidget::eventFilter(QObject *obj, QEvent *event) && (obj == mDisasTextEdit || obj == mDisasTextEdit->viewport())) { QMouseEvent *mouseEvent = static_cast(event); - const QTextCursor& cursor = mDisasTextEdit->cursorForPosition(QPoint(mouseEvent->x(), mouseEvent->y())); + const QTextCursor &cursor = + mDisasTextEdit->cursorForPosition(QPoint(mouseEvent->x(), mouseEvent->y())); jumpToOffsetUnderCursor(cursor); return true; - } else if (event->type() == QEvent::ToolTip - && obj == mDisasTextEdit->viewport()) { - QHelpEvent *helpEvent = static_cast(event); + } else if (event->type() == QEvent::ToolTip && obj == mDisasTextEdit->viewport()) { + QHelpEvent *helpEvent = static_cast(event); auto cursorForWord = mDisasTextEdit->cursorForPosition(helpEvent->pos()); cursorForWord.select(QTextCursor::WordUnderCursor); @@ -679,27 +665,33 @@ bool DisassemblyWidget::eventFilter(QObject *obj, QEvent *event) if (refs.length()) { if (refs.length() > 1) { qWarning() << tr("More than one (%1) references here. Weird behaviour expected.") - .arg(refs.length()); + .arg(refs.length()); } - offsetTo = refs.at(0).to; //This is the offset we want to preview + offsetTo = refs.at(0).to; // This is the offset we want to preview - if(Q_UNLIKELY(offsetFrom != refs.at(0).from)) { + if (Q_UNLIKELY(offsetFrom != refs.at(0).from)) { qWarning() << tr("offsetFrom (%1) differs from refs.at(0).from (%(2))") - .arg(offsetFrom).arg(refs.at(0).from); + .arg(offsetFrom) + .arg(refs.at(0).from); } // Only if the offset we point *to* is different from the one the cursor is currently // on *and* the former is a valid offset, we are allowed to get a preview of offsetTo - if(offsetTo != offsetFrom && offsetTo != RVA_INVALID) { + if (offsetTo != offsetFrom && offsetTo != RVA_INVALID) { QStringList disasmPreview = Core()->getDisassemblyPreview(offsetTo, 10); // Last check to make sure the returned preview isn't an empty text (QStringList) if (!disasmPreview.isEmpty()) { const QFont &fnt = Config()->getFont(); - QFontMetrics fm{ fnt }; + QFontMetrics fm { fnt }; - QString tooltip = QString("
Disassembly Preview:
%3
") - .arg(fnt.family()).arg(qMax(6, fnt.pointSize() - 1)).arg(disasmPreview.join("
")); + QString tooltip = + QString("
Disassembly Preview:
%3
") + .arg(fnt.family()) + .arg(qMax(6, fnt.pointSize() - 1)) + .arg(disasmPreview.join("
")); QToolTip::showText(helpEvent->globalPos(), tooltip, this, QRect(), 3500); } } @@ -713,7 +705,7 @@ bool DisassemblyWidget::eventFilter(QObject *obj, QEvent *event) void DisassemblyWidget::keyPressEvent(QKeyEvent *event) { - if(event->key() == Qt::Key_Return) { + if (event->key() == Qt::Key_Return) { const QTextCursor cursor = mDisasTextEdit->textCursor(); jumpToOffsetUnderCursor(cursor); } @@ -733,8 +725,7 @@ void DisassemblyWidget::on_seekChanged(RVA offset) cursorCharOffset = 0; } - if (topOffset != RVA_INVALID - && offset >= topOffset && offset <= bottomOffset) { + if (topOffset != RVA_INVALID && offset >= topOffset && offset <= bottomOffset) { // if the line with the seek offset is currently visible, just move the cursor there updateCursorPosition(); } else { @@ -764,17 +755,14 @@ void DisassemblyWidget::setupFonts() mDisasTextEdit->setFont(Config()->getFont()); } - void DisassemblyWidget::setupColors() { mDisasTextEdit->setStyleSheet(QString("QPlainTextEdit { background-color: %1; color: %2; }") - .arg(ConfigColor("gui.background").name()) - .arg(ConfigColor("btext").name())); + .arg(ConfigColor("gui.background").name()) + .arg(ConfigColor("btext").name())); } -DisassemblyScrollArea::DisassemblyScrollArea(QWidget *parent) : QAbstractScrollArea(parent) -{ -} +DisassemblyScrollArea::DisassemblyScrollArea(QWidget *parent) : QAbstractScrollArea(parent) {} bool DisassemblyScrollArea::viewportEvent(QEvent *event) { @@ -801,8 +789,7 @@ void DisassemblyScrollArea::resetScrollBars() qreal DisassemblyTextEdit::textOffset() const { - return (blockBoundingGeometry(document()->begin()).topLeft() + - contentOffset()).y(); + return (blockBoundingGeometry(document()->begin()).topLeft() + contentOffset()).y(); } bool DisassemblyTextEdit::viewportEvent(QEvent *event) @@ -825,7 +812,7 @@ void DisassemblyTextEdit::scrollContentsBy(int dx, int dy) void DisassemblyTextEdit::keyPressEvent(QKeyEvent *event) { Q_UNUSED(event) - //QPlainTextEdit::keyPressEvent(event); + // QPlainTextEdit::keyPressEvent(event); } void DisassemblyTextEdit::mousePressEvent(QMouseEvent *event) @@ -846,21 +833,19 @@ void DisassemblyWidget::seekPrev() * Left panel *********************/ -struct Range { - Range(RVA v1, RVA v2) - : from(v1), to(v2) { if (from > to) std::swap(from, to); } +struct Range +{ + Range(RVA v1, RVA v2) : from(v1), to(v2) + { + if (from > to) + std::swap(from, to); + } RVA from; RVA to; - inline bool contains(const Range& other) const - { - return from <= other.from && to >= other.to; - } + inline bool contains(const Range &other) const { return from <= other.from && to >= other.to; } - inline bool contains(RVA point) const - { - return from <= point && to >= point; - } + inline bool contains(RVA point) const { return from <= point && to >= point; } }; DisassemblyLeftPanel::DisassemblyLeftPanel(DisassemblyWidget *disas) @@ -868,7 +853,8 @@ DisassemblyLeftPanel::DisassemblyLeftPanel(DisassemblyWidget *disas) this->disas = disas; } -void DisassemblyLeftPanel::wheelEvent(QWheelEvent *event) { +void DisassemblyLeftPanel::wheelEvent(QWheelEvent *event) +{ int count = -(event->angleDelta() / 15).y(); count -= (count > 0 ? 5 : -5); @@ -884,7 +870,7 @@ void DisassemblyLeftPanel::paintEvent(QPaintEvent *event) constexpr int distanceBetweenLines = 10; constexpr int arrowWidth = 5; int rightOffset = size().rwidth(); - auto tEdit = qobject_cast(disas->getTextWidget()); + auto tEdit = qobject_cast(disas->getTextWidget()); int topOffset = int(tEdit->contentsMargins().top() + tEdit->textOffset()); int lineHeight = disas->getFontMetrics().height(); QColor arrowColorDown = ConfigColor("flow"); @@ -900,7 +886,7 @@ void DisassemblyLeftPanel::paintEvent(QPaintEvent *event) QMap linesPixPosition; QMap> arrowInfo; /* offset -> (arrow, layer of arrow) */ int nLines = 0; - for (const auto& line : lines) { + for (const auto &line : lines) { linesPixPosition[line.offset] = nLines * lineHeight + lineHeight / 2 + topOffset; nLines++; if (line.arrow != RVA_INVALID) { @@ -910,9 +896,7 @@ void DisassemblyLeftPanel::paintEvent(QPaintEvent *event) for (auto it = arrowInfo.begin(); it != arrowInfo.end(); it++) { Range currRange = { it.key(), it.value().first }; - it.value().second = it.value().second == -1 - ? 1 - : it.value().second; + it.value().second = it.value().second == -1 ? 1 : it.value().second; for (auto innerIt = arrowInfo.begin(); innerIt != arrowInfo.end(); innerIt++) { if (innerIt == it) { continue; @@ -936,8 +920,8 @@ void DisassemblyLeftPanel::paintEvent(QPaintEvent *event) continue; } Range innerRange = { innerIt.key(), innerIt.value().first }; - if (it.value().second == innerIt.value().second && - (currRange.contains(innerRange) || currRange.contains(innerRange.from))) { + if (it.value().second == innerIt.value().second + && (currRange.contains(innerRange) || currRange.contains(innerRange.from))) { it.value().second++; correction = true; } @@ -959,9 +943,10 @@ void DisassemblyLeftPanel::paintEvent(QPaintEvent *event) const RVA currOffset = disas->getSeekable()->getOffset(); qreal pixelRatio = qhelpers::devicePixelRatio(p.device()); // Draw the lines - for (const auto& l : lines) { - int lineOffset = int((distanceBetweenLines * arrowInfo[l.offset].second + distanceBetweenLines) * - pixelRatio); + for (const auto &l : lines) { + int lineOffset = + int((distanceBetweenLines * arrowInfo[l.offset].second + distanceBetweenLines) + * pixelRatio); // Skip until we reach a line that jumps to a destination if (l.arrow == RVA_INVALID) { continue; @@ -980,9 +965,7 @@ void DisassemblyLeftPanel::paintEvent(QPaintEvent *event) int lineArrowY = linesPixPosition.value(l.arrow, -1); if (lineArrowY == -1) { - lineArrowY = jumpDown - ? geometry().bottom() - : 0; + lineArrowY = jumpDown ? geometry().bottom() : 0; endVisible = false; } diff --git a/src/widgets/DisassemblyWidget.h b/src/widgets/DisassemblyWidget.h index e4b6eead..eaffa5a1 100644 --- a/src/widgets/DisassemblyWidget.h +++ b/src/widgets/DisassemblyWidget.h @@ -12,7 +12,6 @@ #include #include - class DisassemblyTextEdit; class DisassemblyScrollArea; class DisassemblyContextMenu; @@ -29,7 +28,7 @@ public: public slots: /** - * @brief Highlights the currently selected line and updates the + * @brief Highlights the currently selected line and updates the * highlighting of the same words under the cursor in the visible screen. * This overrides all previous highlighting. */ @@ -98,7 +97,7 @@ private: void moveCursorRelative(bool up, bool page); - void jumpToOffsetUnderCursor(const QTextCursor&); + void jumpToOffsetUnderCursor(const QTextCursor &); }; class DisassemblyScrollArea : public QAbstractScrollArea @@ -119,22 +118,20 @@ private: void resetScrollBars(); }; - -class DisassemblyTextEdit: public QPlainTextEdit +class DisassemblyTextEdit : public QPlainTextEdit { Q_OBJECT public: explicit DisassemblyTextEdit(QWidget *parent = nullptr) - : QPlainTextEdit(parent), - lockScroll(false) {} - - void setLockScroll(bool lock) + : QPlainTextEdit(parent), lockScroll(false) { - this->lockScroll = lock; } + void setLockScroll(bool lock) { this->lockScroll = lock; } + qreal textOffset() const; + protected: bool viewportEvent(QEvent *event) override; void scrollContentsBy(int dx, int dy) override; @@ -149,7 +146,7 @@ private: * This class is used to draw the left pane of the disassembly * widget. Its goal is to draw proper arrows for the jumps of the disassembly. */ -class DisassemblyLeftPanel: public QFrame +class DisassemblyLeftPanel : public QFrame { public: DisassemblyLeftPanel(DisassemblyWidget *disas); diff --git a/src/widgets/EntrypointWidget.cpp b/src/widgets/EntrypointWidget.cpp index f9a335c6..a331d1b8 100644 --- a/src/widgets/EntrypointWidget.cpp +++ b/src/widgets/EntrypointWidget.cpp @@ -7,14 +7,12 @@ #include #include - /* * Entrypoint Widget */ -EntrypointWidget::EntrypointWidget(MainWindow *main) : - CutterDockWidget(main), - ui(new Ui::EntrypointWidget) +EntrypointWidget::EntrypointWidget(MainWindow *main) + : CutterDockWidget(main), ui(new Ui::EntrypointWidget) { ui->setupUi(this); @@ -45,8 +43,7 @@ void EntrypointWidget::setScrollMode() qhelpers::setVerticalScrollMode(ui->entrypointTreeWidget); } -void EntrypointWidget::on_entrypointTreeWidget_itemDoubleClicked(QTreeWidgetItem *item, - int column) +void EntrypointWidget::on_entrypointTreeWidget_itemDoubleClicked(QTreeWidgetItem *item, int column) { if (column < 0) return; diff --git a/src/widgets/ExportsWidget.cpp b/src/widgets/ExportsWidget.cpp index 1859b331..8eee5207 100644 --- a/src/widgets/ExportsWidget.cpp +++ b/src/widgets/ExportsWidget.cpp @@ -7,8 +7,7 @@ #include ExportsModel::ExportsModel(QList *exports, QObject *parent) - : AddressableItemModel(parent), - exports(exports) + : AddressableItemModel(parent), exports(exports) { } @@ -134,8 +133,7 @@ bool ExportsProxyModel::lessThan(const QModelIndex &left, const QModelIndex &rig return leftExp.vaddr < rightExp.vaddr; } -ExportsWidget::ExportsWidget(MainWindow *main) : - ListDockWidget(main) +ExportsWidget::ExportsWidget(MainWindow *main) : ListDockWidget(main) { setWindowTitle(tr("Exports")); setObjectName("ExportsWidget"); @@ -146,15 +144,12 @@ ExportsWidget::ExportsWidget(MainWindow *main) : ui->treeView->sortByColumn(ExportsModel::OffsetColumn, Qt::AscendingOrder); QShortcut *toggle_shortcut = new QShortcut(widgetShortcuts["ExportsWidget"], main); - connect(toggle_shortcut, &QShortcut::activated, this, [=] (){ - toggleDockWidget(true); - } ); + connect(toggle_shortcut, &QShortcut::activated, this, [=]() { toggleDockWidget(true); }); connect(Core(), &CutterCore::codeRebased, this, &ExportsWidget::refreshExports); connect(Core(), &CutterCore::refreshAll, this, &ExportsWidget::refreshExports); - connect(Core(), &CutterCore::commentsChanged, this, [this]() { - qhelpers::emitColumnChanged(exportsModel, ExportsModel::CommentColumn); - }); + connect(Core(), &CutterCore::commentsChanged, this, + [this]() { qhelpers::emitColumnChanged(exportsModel, ExportsModel::CommentColumn); }); } ExportsWidget::~ExportsWidget() {} diff --git a/src/widgets/ExportsWidget.h b/src/widgets/ExportsWidget.h index 2025a10b..a829cb64 100644 --- a/src/widgets/ExportsWidget.h +++ b/src/widgets/ExportsWidget.h @@ -28,7 +28,14 @@ private: QList *exports; public: - enum Column { OffsetColumn = 0, SizeColumn, TypeColumn, NameColumn, CommentColumn, ColumnCount }; + enum Column { + OffsetColumn = 0, + SizeColumn, + TypeColumn, + NameColumn, + CommentColumn, + ColumnCount + }; enum Role { ExportDescriptionRole = Qt::UserRole }; ExportsModel(QList *exports, QObject *parent = nullptr); @@ -37,7 +44,8 @@ public: int columnCount(const QModelIndex &parent = QModelIndex()) const override; QVariant data(const QModelIndex &index, int role) const override; - QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; + QVariant headerData(int section, Qt::Orientation orientation, + int role = Qt::DisplayRole) const override; RVA address(const QModelIndex &index) const override; QString name(const QModelIndex &index) const override; diff --git a/src/widgets/FlagsWidget.cpp b/src/widgets/FlagsWidget.cpp index 0cbdcc09..792ab435 100644 --- a/src/widgets/FlagsWidget.cpp +++ b/src/widgets/FlagsWidget.cpp @@ -11,8 +11,7 @@ #include FlagsModel::FlagsModel(QList *flags, QObject *parent) - : AddressableItemModel(parent), - flags(flags) + : AddressableItemModel(parent), flags(flags) { } @@ -128,7 +127,7 @@ bool FlagsSortFilterProxyModel::lessThan(const QModelIndex &left, const QModelIn // fallthrough case FlagsModel::NAME: return left_flag->name < right_flag->name; - + case FlagsModel::REALNAME: return left_flag->realname < right_flag->realname; @@ -143,12 +142,8 @@ bool FlagsSortFilterProxyModel::lessThan(const QModelIndex &left, const QModelIn return left_flag->offset < right_flag->offset; } - -FlagsWidget::FlagsWidget(MainWindow *main) : - CutterDockWidget(main), - ui(new Ui::FlagsWidget), - main(main), - tree(new CutterTreeWidget(this)) +FlagsWidget::FlagsWidget(MainWindow *main) + : CutterDockWidget(main), ui(new Ui::FlagsWidget), main(main), tree(new CutterTreeWidget(this)) { ui->setupUi(this); @@ -157,15 +152,16 @@ FlagsWidget::FlagsWidget(MainWindow *main) : flags_model = new FlagsModel(&flags, this); flags_proxy_model = new FlagsSortFilterProxyModel(flags_model, this); - connect(ui->filterLineEdit, &QLineEdit::textChanged, - flags_proxy_model, &QSortFilterProxyModel::setFilterWildcard); + connect(ui->filterLineEdit, &QLineEdit::textChanged, flags_proxy_model, + &QSortFilterProxyModel::setFilterWildcard); ui->flagsTreeView->setMainWindow(mainWindow); ui->flagsTreeView->setModel(flags_proxy_model); ui->flagsTreeView->sortByColumn(FlagsModel::OFFSET, Qt::AscendingOrder); // Ctrl-F to move the focus to the Filter search box QShortcut *searchShortcut = new QShortcut(QKeySequence::Find, this); - connect(searchShortcut, &QShortcut::activated, ui->filterLineEdit, [this]() { ui->filterLineEdit->setFocus(); }); + connect(searchShortcut, &QShortcut::activated, ui->filterLineEdit, + [this]() { ui->filterLineEdit->setFocus(); }); searchShortcut->setContext(Qt::WidgetWithChildrenShortcut); // Esc to clear the filter entry @@ -179,18 +175,16 @@ FlagsWidget::FlagsWidget(MainWindow *main) : }); clearShortcut->setContext(Qt::WidgetWithChildrenShortcut); - connect(ui->filterLineEdit, &QLineEdit::textChanged, this, [this] { - tree->showItemsNumber(flags_proxy_model->rowCount()); - }); + connect(ui->filterLineEdit, &QLineEdit::textChanged, this, + [this] { tree->showItemsNumber(flags_proxy_model->rowCount()); }); setScrollMode(); connect(Core(), &CutterCore::flagsChanged, this, &FlagsWidget::flagsChanged); connect(Core(), &CutterCore::codeRebased, this, &FlagsWidget::flagsChanged); connect(Core(), &CutterCore::refreshAll, this, &FlagsWidget::refreshFlagspaces); - connect(Core(), &CutterCore::commentsChanged, this, [this]() { - qhelpers::emitColumnChanged(flags_model, FlagsModel::COMMENT); - }); + connect(Core(), &CutterCore::commentsChanged, this, + [this]() { qhelpers::emitColumnChanged(flags_model, FlagsModel::COMMENT); }); auto menu = ui->flagsTreeView->getItemContextMenu(); menu->addSeparator(); @@ -211,12 +205,14 @@ void FlagsWidget::on_flagspaceCombo_currentTextChanged(const QString &arg1) void FlagsWidget::on_actionRename_triggered() { - FlagDescription flag = ui->flagsTreeView->selectionModel()->currentIndex().data( - FlagsModel::FlagDescriptionRole).value(); + FlagDescription flag = ui->flagsTreeView->selectionModel() + ->currentIndex() + .data(FlagsModel::FlagDescriptionRole) + .value(); bool ok; QString newName = QInputDialog::getText(this, tr("Rename flag %1").arg(flag.name), - tr("Flag name:"), QLineEdit::Normal, flag.name, &ok); + tr("Flag name:"), QLineEdit::Normal, flag.name, &ok); if (ok && !newName.isEmpty()) { Core()->renameFlag(flag.name, newName); } @@ -224,8 +220,10 @@ void FlagsWidget::on_actionRename_triggered() void FlagsWidget::on_actionDelete_triggered() { - FlagDescription flag = ui->flagsTreeView->selectionModel()->currentIndex().data( - FlagsModel::FlagDescriptionRole).value(); + FlagDescription flag = ui->flagsTreeView->selectionModel() + ->currentIndex() + .data(FlagsModel::FlagDescriptionRole) + .value(); Core()->delFlag(flag.name); } @@ -240,7 +238,8 @@ void FlagsWidget::refreshFlagspaces() if (cur_idx < 0) cur_idx = 0; - disableFlagRefresh = true; // prevent duplicate flag refresh caused by flagspaceCombo modifications + disableFlagRefresh = + true; // prevent duplicate flag refresh caused by flagspaceCombo modifications ui->flagspaceCombo->clear(); ui->flagspaceCombo->addItem(tr("(all)")); @@ -266,7 +265,6 @@ void FlagsWidget::refreshFlags() if (flagspace_data.isValid()) flagspace = flagspace_data.value().name; - flags_model->beginResetModel(); flags = Core()->getAllFlags(flagspace); flags_model->endResetModel(); diff --git a/src/widgets/FlagsWidget.h b/src/widgets/FlagsWidget.h index 8d37a997..e2fdcaa9 100644 --- a/src/widgets/FlagsWidget.h +++ b/src/widgets/FlagsWidget.h @@ -17,8 +17,7 @@ class MainWindow; class QTreeWidgetItem; class FlagsWidget; - -class FlagsModel: public AddressableItemModel +class FlagsModel : public AddressableItemModel { friend FlagsWidget; @@ -44,8 +43,6 @@ public: const FlagDescription *description(QModelIndex index) const; }; - - class FlagsSortFilterProxyModel : public AddressableFilterProxyModel { Q_OBJECT @@ -58,8 +55,6 @@ protected: bool lessThan(const QModelIndex &left, const QModelIndex &right) const override; }; - - namespace Ui { class FlagsWidget; } diff --git a/src/widgets/FunctionsWidget.cpp b/src/widgets/FunctionsWidget.cpp index d69aefb4..f5875ee3 100644 --- a/src/widgets/FunctionsWidget.cpp +++ b/src/widgets/FunctionsWidget.cpp @@ -27,7 +27,8 @@ static const int kMaxTooltipHighlightsLines = 5; } FunctionModel::FunctionModel(QList *functions, QSet *importAddresses, - ut64 *mainAdress, bool nested, QFont default_font, QFont highlight_font, QObject *parent) + ut64 *mainAdress, bool nested, QFont default_font, + QFont highlight_font, QObject *parent) : AddressableItemModel<>(parent), functions(functions), importAddresses(importAddresses), @@ -39,8 +40,7 @@ FunctionModel::FunctionModel(QList *functions, QSet *i { connect(Core(), &CutterCore::seekChanged, this, &FunctionModel::seekChanged); - connect(Core(), &CutterCore::functionRenamed, - this, &FunctionModel::functionRenamed); + connect(Core(), &CutterCore::functionRenamed, this, &FunctionModel::functionRenamed); } QModelIndex FunctionModel::index(int row, int column, const QModelIndex &parent) const @@ -76,7 +76,7 @@ int FunctionModel::rowCount(const QModelIndex &parent) const return 0; } -int FunctionModel::columnCount(const QModelIndex &/*parent*/) const +int FunctionModel::columnCount(const QModelIndex & /*parent*/) const { if (nested) return 1; @@ -124,7 +124,8 @@ QVariant FunctionModel::data(const QModelIndex &index, int role) const case 1: return tr("Size: %1").arg(RSizeString(function.linearSize)); case 2: - return tr("Import: %1").arg(functionIsImport(function.offset) ? tr("true") : tr("false")); + return tr("Import: %1") + .arg(functionIsImport(function.offset) ? tr("true") : tr("false")); case 3: return tr("Nargs: %1").arg(RSizeString(function.nargs)); case 4: @@ -172,8 +173,8 @@ QVariant FunctionModel::data(const QModelIndex &index, int role) const } case Qt::DecorationRole: - if (importAddresses->contains(function.offset) && - (nested ? false : index.column() == ImportColumn)) { + if (importAddresses->contains(function.offset) + && (nested ? false : index.column() == ImportColumn)) { const static QIcon importIcon(":/img/icons/import_light.svg"); return importIcon; } @@ -191,11 +192,11 @@ QVariant FunctionModel::data(const QModelIndex &index, int role) const case Qt::ToolTipRole: { - QStringList disasmPreview = Core()->getDisassemblyPreview(function.offset, - kMaxTooltipDisasmPreviewLines); + QStringList disasmPreview = + Core()->getDisassemblyPreview(function.offset, kMaxTooltipDisasmPreviewLines); const QStringList &summary = Core()->cmdList(QString("pdsf @ %1").arg(function.offset)); const QFont &fnt = Config()->getFont(); - QFontMetrics fm{ fnt }; + QFontMetrics fm { fnt }; // elide long strings using current disasm font metrics QStringList highlights; @@ -210,19 +211,22 @@ QVariant FunctionModel::data(const QModelIndex &index, int role) const return QVariant(); QString toolTipContent = - QString("
") - .arg(fnt.family()) - .arg(qMax(6, fnt.pointSize() - - 1)); // slightly decrease font size, to keep more text in the same box + QString("
") + .arg(fnt.family()) + .arg(qMax(6, fnt.pointSize() - 1)); // slightly decrease font size, to keep + // more text in the same box if (!disasmPreview.isEmpty()) - toolTipContent += - tr("
Disassembly preview:
%1
") - .arg(disasmPreview.join("
")); + toolTipContent += tr("
Disassembly " + "preview:
%1
") + .arg(disasmPreview.join("
")); if (!highlights.isEmpty()) { toolTipContent += tr("
Highlights:
%1
") - .arg(highlights.join(QLatin1Char('\n')).toHtmlEscaped().replace(QLatin1Char('\n'), "
")); + .arg(highlights.join(QLatin1Char('\n')) + .toHtmlEscaped() + .replace(QLatin1Char('\n'), "
")); } toolTipContent += "
"; return toolTipContent; @@ -327,8 +331,7 @@ bool FunctionModel::updateCurrentIndex() for (int i = 0; i < functions->count(); i++) { const FunctionDescription &function = functions->at(i); - if (function.contains(seek) - && function.offset >= offset) { + if (function.contains(seek) && function.offset >= offset) { offset = function.offset; index = i; } @@ -363,8 +366,8 @@ FunctionSortFilterProxyModel::FunctionSortFilterProxyModel(FunctionModel *source bool FunctionSortFilterProxyModel::filterAcceptsRow(int row, const QModelIndex &parent) const { QModelIndex index = sourceModel()->index(row, 0, parent); - FunctionDescription function = index.data( - FunctionModel::FunctionDescriptionRole).value(); + FunctionDescription function = + index.data(FunctionModel::FunctionDescriptionRole).value(); return function.name.contains(filterRegExp()); } @@ -376,11 +379,10 @@ bool FunctionSortFilterProxyModel::lessThan(const QModelIndex &left, const QMode if (left.parent().isValid() || right.parent().isValid()) return false; - FunctionDescription left_function = left.data( - FunctionModel::FunctionDescriptionRole).value(); - FunctionDescription right_function = right.data( - FunctionModel::FunctionDescriptionRole).value(); - + FunctionDescription left_function = + left.data(FunctionModel::FunctionDescriptionRole).value(); + FunctionDescription right_function = + right.data(FunctionModel::FunctionDescriptionRole).value(); if (static_cast(sourceModel())->isNested()) { return left_function.name < right_function.name; @@ -424,7 +426,8 @@ bool FunctionSortFilterProxyModel::lessThan(const QModelIndex &left, const QMode return left_function.stackframe < right_function.stackframe; break; case FunctionModel::CommentColumn: - return Core()->getCommentAt(left_function.offset) < Core()->getCommentAt(right_function.offset); + return Core()->getCommentAt(left_function.offset) + < Core()->getCommentAt(right_function.offset); default: return false; } @@ -433,12 +436,12 @@ bool FunctionSortFilterProxyModel::lessThan(const QModelIndex &left, const QMode } } -FunctionsWidget::FunctionsWidget(MainWindow *main) : - ListDockWidget(main), - actionRename(tr("Rename"), this), - actionUndefine(tr("Undefine"), this), - actionHorizontal(tr("Horizontal"), this), - actionVertical(tr("Vertical"), this) +FunctionsWidget::FunctionsWidget(MainWindow *main) + : ListDockWidget(main), + actionRename(tr("Rename"), this), + actionUndefine(tr("Undefine"), this), + actionHorizontal(tr("Horizontal"), this), + actionVertical(tr("Vertical"), this) { setWindowTitle(tr("Functions")); setObjectName("FunctionsWidget"); @@ -450,24 +453,24 @@ FunctionsWidget::FunctionsWidget(MainWindow *main) : QFont default_font = QFont(font_info.family(), font_info.pointSize()); QFont highlight_font = QFont(font_info.family(), font_info.pointSize(), QFont::Bold); - functionModel = new FunctionModel(&functions, &importAddresses, &mainAdress, false, default_font, - highlight_font, this); + functionModel = new FunctionModel(&functions, &importAddresses, &mainAdress, false, + default_font, highlight_font, this); functionProxyModel = new FunctionSortFilterProxyModel(functionModel, this); setModels(functionProxyModel); ui->treeView->sortByColumn(FunctionModel::NameColumn, Qt::AscendingOrder); - titleContextMenu = new QMenu(this); auto viewTypeGroup = new QActionGroup(titleContextMenu); actionHorizontal.setCheckable(true); actionHorizontal.setActionGroup(viewTypeGroup); - connect(&actionHorizontal, &QAction::toggled, this, &FunctionsWidget::onActionHorizontalToggled); + connect(&actionHorizontal, &QAction::toggled, this, + &FunctionsWidget::onActionHorizontalToggled); actionVertical.setCheckable(true); actionVertical.setActionGroup(viewTypeGroup); connect(&actionVertical, &QAction::toggled, this, &FunctionsWidget::onActionVerticalToggled); titleContextMenu->addActions(viewTypeGroup->actions()); - actionRename.setShortcut({Qt::Key_N}); + actionRename.setShortcut({ Qt::Key_N }); actionRename.setShortcutContext(Qt::ShortcutContext::WidgetWithChildrenShortcut); connect(&actionRename, &QAction::triggered, this, &FunctionsWidget::onActionFunctionsRenameTriggered); @@ -485,15 +488,14 @@ FunctionsWidget::FunctionsWidget(MainWindow *main) : // Use a custom context menu on the dock title bar actionHorizontal.setChecked(true); this->setContextMenuPolicy(Qt::CustomContextMenu); - connect(this, &QWidget::customContextMenuRequested, - this, &FunctionsWidget::showTitleContextMenu); + connect(this, &QWidget::customContextMenuRequested, this, + &FunctionsWidget::showTitleContextMenu); connect(Core(), &CutterCore::functionsChanged, this, &FunctionsWidget::refreshTree); connect(Core(), &CutterCore::codeRebased, this, &FunctionsWidget::refreshTree); connect(Core(), &CutterCore::refreshAll, this, &FunctionsWidget::refreshTree); - connect(Core(), &CutterCore::commentsChanged, this, [this]() { - qhelpers::emitColumnChanged(functionModel, FunctionModel::CommentColumn); - }); + connect(Core(), &CutterCore::commentsChanged, this, + [this]() { qhelpers::emitColumnChanged(functionModel, FunctionModel::CommentColumn); }); } FunctionsWidget::~FunctionsWidget() {} @@ -505,25 +507,25 @@ void FunctionsWidget::refreshTree() } task = QSharedPointer(new FunctionsTask()); - connect(task.data(), &FunctionsTask::fetchFinished, - this, [this] (const QList &functions) { - functionModel->beginResetModel(); + connect(task.data(), &FunctionsTask::fetchFinished, this, + [this](const QList &functions) { + functionModel->beginResetModel(); - this->functions = functions; + this->functions = functions; - importAddresses.clear(); - for (const ImportDescription &import : Core()->getAllImports()) { - importAddresses.insert(import.plt); - } + importAddresses.clear(); + for (const ImportDescription &import : Core()->getAllImports()) { + importAddresses.insert(import.plt); + } - mainAdress = (ut64)Core()->cmdj("iMj").object()["vaddr"].toInt(); + mainAdress = (ut64)Core()->cmdj("iMj").object()["vaddr"].toInt(); - functionModel->updateCurrentIndex(); - functionModel->endResetModel(); + functionModel->updateCurrentIndex(); + functionModel->endResetModel(); - // resize offset and size columns - qhelpers::adjustColumns(ui->treeView, 3, 0); - }); + // resize offset and size columns + qhelpers::adjustColumns(ui->treeView, 3, 0); + }); Core()->getAsyncTaskManager()->start(task); } @@ -535,13 +537,16 @@ void FunctionsWidget::changeSizePolicy(QSizePolicy::Policy hor, QSizePolicy::Pol void FunctionsWidget::onActionFunctionsRenameTriggered() { // Get selected item in functions tree view - FunctionDescription function = ui->treeView->selectionModel()->currentIndex().data( - FunctionModel::FunctionDescriptionRole).value(); + FunctionDescription function = ui->treeView->selectionModel() + ->currentIndex() + .data(FunctionModel::FunctionDescriptionRole) + .value(); bool ok; // Create dialog - QString newName = QInputDialog::getText(this, tr("Rename function %1").arg(function.name), - tr("Function name:"), QLineEdit::Normal, function.name, &ok); + QString newName = + QInputDialog::getText(this, tr("Rename function %1").arg(function.name), + tr("Function name:"), QLineEdit::Normal, function.name, &ok); // If user accepted if (ok && !newName.isEmpty()) { // Rename function in rizin core @@ -552,7 +557,6 @@ void FunctionsWidget::onActionFunctionsRenameTriggered() } } - void FunctionsWidget::onActionFunctionsUndefineTriggered() { const auto selection = ui->treeView->selectionModel()->selection().indexes(); @@ -592,10 +596,10 @@ void FunctionsWidget::onActionVerticalToggled(bool enable) */ void FunctionsWidget::setTooltipStylesheet() { - setStyleSheet(QString("QToolTip { border-width: 1px; max-width: %1px;" \ - "opacity: 230; background-color: %2;" \ + setStyleSheet(QString("QToolTip { border-width: 1px; max-width: %1px;" + "opacity: 230; background-color: %2;" "color: %3; border-color: %3;}") - .arg(kMaxTooltipWidth) - .arg(Config()->getColor("gui.tooltip.background").name()) - .arg(Config()->getColor("gui.tooltip.foreground").name())); + .arg(kMaxTooltipWidth) + .arg(Config()->getColor("gui.tooltip.background").name()) + .arg(Config()->getColor("gui.tooltip.foreground").name())); } diff --git a/src/widgets/FunctionsWidget.h b/src/widgets/FunctionsWidget.h index ae4de3a6..99ab7656 100644 --- a/src/widgets/FunctionsWidget.h +++ b/src/widgets/FunctionsWidget.h @@ -22,7 +22,6 @@ private: QSet *importAddresses; ut64 *mainAdress; - QFont highlightFont; QFont defaultFont; bool nested; @@ -37,14 +36,27 @@ public: static const int FunctionDescriptionRole = Qt::UserRole; static const int IsImportRole = Qt::UserRole + 1; - enum Column { NameColumn = 0, SizeColumn, ImportColumn, OffsetColumn, NargsColumn, NlocalsColumn, - NbbsColumn, CalltypeColumn, EdgesColumn, FrameColumn, CommentColumn, ColumnCount - }; + enum Column { + NameColumn = 0, + SizeColumn, + ImportColumn, + OffsetColumn, + NargsColumn, + NlocalsColumn, + NbbsColumn, + CalltypeColumn, + EdgesColumn, + FrameColumn, + CommentColumn, + ColumnCount + }; - FunctionModel(QList *functions, QSet *importAddresses, ut64 *mainAdress, - bool nested, QFont defaultFont, QFont highlightFont, QObject *parent = nullptr); + FunctionModel(QList *functions, QSet *importAddresses, + ut64 *mainAdress, bool nested, QFont defaultFont, QFont highlightFont, + QObject *parent = nullptr); - QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const override; + QModelIndex index(int row, int column, + const QModelIndex &parent = QModelIndex()) const override; QModelIndex parent(const QModelIndex &index) const override; int rowCount(const QModelIndex &parent = QModelIndex()) const override; @@ -60,10 +72,7 @@ public: bool updateCurrentIndex(); void setNested(bool nested); - bool isNested() - { - return nested; - } + bool isNested() { return nested; } RVA address(const QModelIndex &index) const override; QString name(const QModelIndex &index) const override; @@ -72,7 +81,6 @@ private slots: void functionRenamed(const RVA offset, const QString &new_name); }; - class FunctionSortFilterProxyModel : public AddressableFilterProxyModel { Q_OBJECT @@ -85,8 +93,6 @@ protected: bool lessThan(const QModelIndex &left, const QModelIndex &right) const override; }; - - class FunctionsWidget : public ListDockWidget { Q_OBJECT diff --git a/src/widgets/GraphGridLayout.cpp b/src/widgets/GraphGridLayout.cpp index 312dd183..47d8e89d 100644 --- a/src/widgets/GraphGridLayout.cpp +++ b/src/widgets/GraphGridLayout.cpp @@ -9,98 +9,108 @@ #include "common/BinaryTrees.h" - /** @class GraphGridLayout Basic familiarity with graph algorithms is recommended. # Terms used: -- **Vertex**, **node**, **block** - read description of graph for definition. Within this text vertex and node are -used interchangeably with block due to code being written for visualizing basic block control flow graph. +- **Vertex**, **node**, **block** - read description of graph for definition. Within this text +vertex and node are used interchangeably with block due to code being written for visualizing basic +block control flow graph. - **edge** - read description of graph for definition for precise definition. -- **DAG** - directed acyclic graph, graph using directed edges which doesn't have cycles. DAG may contain loops if -following them would require going in both directions of edges. Example 1->2 1->3 3->2 is a DAG, 2->1 1->3 3->2 -isn't a DAG. +- **DAG** - directed acyclic graph, graph using directed edges which doesn't have cycles. DAG may +contain loops if following them would require going in both directions of edges. Example 1->2 1->3 +3->2 is a DAG, 2->1 1->3 3->2 isn't a DAG. - **DFS** - depth first search, a graph traversal algorithm -- **toposort** - topological sorting, process of ordering a DAG vertices that all edges go from vertices earlier in the -toposort order to vertices later in toposort order. There are multiple algorithms for implementing toposort operation. -Single DAG can have multiple valid topological orderings, a toposort algorithm can be designed to prioritize a specific -one from all valid toposort orders. Example: for graph 1->4, 2->1, 2->3, 3->4 valid topological orders are [2,1,3,4] and +- **toposort** - topological sorting, process of ordering a DAG vertices that all edges go from +vertices earlier in the toposort order to vertices later in toposort order. There are multiple +algorithms for implementing toposort operation. Single DAG can have multiple valid topological +orderings, a toposort algorithm can be designed to prioritize a specific one from all valid toposort +orders. Example: for graph 1->4, 2->1, 2->3, 3->4 valid topological orders are [2,1,3,4] and [2,3,1,4]. # High level structure of the algorithm 1. select subset of edges that form a DAG (remove cycles) 2. toposort the DAG 3. choose a subset of edges that form a tree and assign layers -4. assign node positions within grid using tree structure, child subtrees are placed side by side with parent on top +4. assign node positions within grid using tree structure, child subtrees are placed side by side +with parent on top 5. perform edge routing 6. calculate column and row pixel positions based on node sizes and amount edges between the rows 7. [optional] layout compacting -Contrary to many other layered graph drawing algorithm this implementation doesn't perform node reordering to minimize -edge crossing. This simplifies implementation, and preserves original control flow structure for conditional jumps ( -true jump on one side, false jump on other). Due to most of control flow being result of structured programming -constructs like if/then/else and loops, resulting layout is usually readable without node reordering within layers. +Contrary to many other layered graph drawing algorithm this implementation doesn't perform node +reordering to minimize edge crossing. This simplifies implementation, and preserves original control +flow structure for conditional jumps ( true jump on one side, false jump on other). Due to most of +control flow being result of structured programming constructs like if/then/else and loops, +resulting layout is usually readable without node reordering within layers. # Description of grid. -To simplify the layout algorithm initial steps assume that all nodes have the same size and edges are zero width. -After placing the nodes and routing the edges it is known which nodes are in in which row and column, how -many edges are between each pair of rows. Using this information positions are converted from the grid cells -to pixel coordinates. Routing 0 width edges between rows can also be interpreted as every second row and column being -reserved for edges. The row numbers in code are using first interpretation. To allow better centering of nodes one -above other each node is 2 columns wide and 1 row high. +To simplify the layout algorithm initial steps assume that all nodes have the same size and edges +are zero width. After placing the nodes and routing the edges it is known which nodes are in in +which row and column, how many edges are between each pair of rows. Using this information positions +are converted from the grid cells to pixel coordinates. Routing 0 width edges between rows can also +be interpreted as every second row and column being reserved for edges. The row numbers in code are +using first interpretation. To allow better centering of nodes one above other each node is 2 +columns wide and 1 row high. \image html graph_grid.svg # 1-2 Cycle removal and toposort -Cycle removal and toposort are done at the same time during single DFS traversal. In case entrypoint is part of a loop -DFS started from entrypoint. This ensures that entrypoint is at the top of resulting layout if possible. Resulting -toposort order is used in many of the following layout steps that require calculating some property of a vertex based -on child property or the other way around. Using toposort order such operations can be implemented iteration through -array in either forward or reverse direction. To prevent running out of stack memory when processing large graphs -DFS is implemented non-recursively. +Cycle removal and toposort are done at the same time during single DFS traversal. In case entrypoint +is part of a loop DFS started from entrypoint. This ensures that entrypoint is at the top of +resulting layout if possible. Resulting toposort order is used in many of the following layout steps +that require calculating some property of a vertex based on child property or the other way around. +Using toposort order such operations can be implemented iteration through array in either forward or +reverse direction. To prevent running out of stack memory when processing large graphs DFS is +implemented non-recursively. # Row assignment -Rows are assigned in toposort order from top to bottom, with nodes row being max(predecessor.row)+1. This ensures -that loop edges are only ones going from deeper levels to previous layers. +Rows are assigned in toposort order from top to bottom, with nodes row being max(predecessor.row)+1. +This ensures that loop edges are only ones going from deeper levels to previous layers. -To further simply node placement a subset of edges is selected which forms a tree. This turns DAG drawing problem -into a tree drawing problem. For each node in level n following nodes which have level exactly n+1 are greedily -assigned as child nodes in tree. If a node already has parent assigned then corresponding edge is not part of tree. +To further simply node placement a subset of edges is selected which forms a tree. This turns DAG +drawing problem into a tree drawing problem. For each node in level n following nodes which have +level exactly n+1 are greedily assigned as child nodes in tree. If a node already has parent +assigned then corresponding edge is not part of tree. # Node position assignment -Since the graph has been reduced to a tree, node placement is more or less putting subtrees side by side with -parent on top. There is some room for interpretation what exactly side by side means and where exactly on top is. -Drawing the graph either too dense or too big may make it less readable so there are configuration options which allow -choosing these things resulting in more or less dense layout. +Since the graph has been reduced to a tree, node placement is more or less putting subtrees side by +side with parent on top. There is some room for interpretation what exactly side by side means and +where exactly on top is. Drawing the graph either too dense or too big may make it less readable so +there are configuration options which allow choosing these things resulting in more or less dense +layout. -Once the subtrees are placed side by side. Parent node can be placed either in the middle of horizontal bounds or -in the middle of direct children. First option results in narrower layout and more vertical columns. Second option -results in nodes being more spread out which may help seeing where each edge goes. +Once the subtrees are placed side by side. Parent node can be placed either in the middle of +horizontal bounds or in the middle of direct children. First option results in narrower layout and +more vertical columns. Second option results in nodes being more spread out which may help seeing +where each edge goes. -In more compact mode two subtrees are placed side by side taking into account their shape. In wider mode -bounding box of shorter subtree is used instead of exact shape. This gives slightly sparse layout without it being too -wide. +In more compact mode two subtrees are placed side by side taking into account their shape. In wider +mode bounding box of shorter subtree is used instead of exact shape. This gives slightly sparse +layout without it being too wide. \image html graph_parent_placement.svg # Edge routing Edge routing can be split into: main column selection, rough routing, segment offset calculation. -Transition from source to target row is done using single vertical segment. This is called main column. +Transition from source to target row is done using single vertical segment. This is called main +column. Rough routing creates the path of edge using up to 5 segments using grid coordinates. Due to nodes being placed in a grid. Horizontal segments of edges can't intersect with any nodes. -The path for edges is chosen so that it consists of at most 5 segments, typically resulting in sideways U shape or -square Z shape. +The path for edges is chosen so that it consists of at most 5 segments, typically resulting in +sideways U shape or square Z shape. - short vertical segment from node to horizontal line - move to empty column -- vertical segment between starting row and end row, an empty column can always be found, in the worst case there are empty columns at the sides of drawing +- vertical segment between starting row and end row, an empty column can always be found, in the +worst case there are empty columns at the sides of drawing - horizontal segment to target node column - short vertical segment connecting to target node @@ -108,55 +118,58 @@ There are 3 special cases: - source and target nodes are in the same column with no nodes between - single vertical segment - column bellow stating node is empty - segments 1-3 are merged - column above target node is empty - segments 3-5 are merged -Vertical segment intersection with nodes is prevented using a 2d array marking which vertical segments are blocked and -naively iterating through all rows between start and end at the desired column. +Vertical segment intersection with nodes is prevented using a 2d array marking which vertical +segments are blocked and naively iterating through all rows between start and end at the desired +column. -After rough routing segment offsets are calculated relative to their corresponding edge column. This ensures that -two segments don't overlap. Segment offsets within each column are assigned greedily with some heuristics for -assignment order to reduce amount of edge crossings and result in more visually pleasing output for a typical CFG -graph. -Each segment gets assigned an offset that is maximum of previously assigned offsets overlapping with current -segment + segment spacing. +After rough routing segment offsets are calculated relative to their corresponding edge column. This +ensures that two segments don't overlap. Segment offsets within each column are assigned greedily +with some heuristics for assignment order to reduce amount of edge crossings and result in more +visually pleasing output for a typical CFG graph. Each segment gets assigned an offset that is +maximum of previously assigned offsets overlapping with current segment + segment spacing. Assignment order is chosen based on: -* direction of previous and last segment - helps reducing crossings and place the segments between nodes -* segment length - reduces crossing when segment endpoints have the same structure as valid parentheses expression -* edge length - establishes some kind of order when single node is connected to many edges, typically a block - with switch statement or block after switch statement. +* direction of previous and last segment - helps reducing crossings and place the segments between +nodes +* segment length - reduces crossing when segment endpoints have the same structure as valid +parentheses expression +* edge length - establishes some kind of order when single node is connected to many edges, +typically a block with switch statement or block after switch statement. # Layout compacting -Doing the layout within a grid causes minimal spacing to be limited by widest and tallest block within each column -and row. One common case is block with function entrypoint being wider due to function name causing wide horizontal -space between branching blocks. Another case is rows in two parallel columns being aligned. +Doing the layout within a grid causes minimal spacing to be limited by widest and tallest block +within each column and row. One common case is block with function entrypoint being wider due to +function name causing wide horizontal space between branching blocks. Another case is rows in two +parallel columns being aligned. \image html layout_compacting.svg -Both problems are mitigated by squishing graph. Compressing in each of the two direction is done separately. -The process is defined as liner program. Each variable represents a position of edge segment or node in the -direction being optimized. +Both problems are mitigated by squishing graph. Compressing in each of the two direction is done +separately. The process is defined as liner program. Each variable represents a position of edge +segment or node in the direction being optimized. Following constraints are used - Keep the order with nearest segments. -- If the node has two outgoing edges, one to the node on left side and other to the right, keep them on the corresponding side of node's center. -- For all edges keep the node which is above above. This helps when vertical block spacing is set bigger than double edge spacing and -edge shadows relationship between two blocks. -- Equality constraint to keep relative position between nodes and and segments directly connected to them. +- If the node has two outgoing edges, one to the node on left side and other to the right, keep them +on the corresponding side of node's center. +- For all edges keep the node which is above above. This helps when vertical block spacing is set +bigger than double edge spacing and edge shadows relationship between two blocks. +- Equality constraint to keep relative position between nodes and and segments directly connected to +them. - Equality constraint to keep the node centered when control flow merges -In the vertical direction objective function minimizes y positions of nodes and lengths of vertical segments. -In the horizontal direction objective function minimizes lengths of horizontal segments. +In the vertical direction objective function minimizes y positions of nodes and lengths of vertical +segments. In the horizontal direction objective function minimizes lengths of horizontal segments. -In the resulting linear program all constraints beside x_i >= 0 consist of exactly two variables: either x_i - x_j <= c_k or -x_i = x_j + c_k. +In the resulting linear program all constraints beside x_i >= 0 consist of exactly two variables: +either x_i - x_j <= c_k or x_i = x_j + c_k. -Since it isn't necessary get perfect solution and to avoid worst case performance current implementation isn't -using a general purpose linear programming solver. Each variable is changed until constraint is reached and afterwards -variables are grouped and changed together. +Since it isn't necessary get perfect solution and to avoid worst case performance current +implementation isn't using a general purpose linear programming solver. Each variable is changed +until constraint is reached and afterwards variables are grouped and changed together. */ - -GraphGridLayout::GraphGridLayout(GraphGridLayout::LayoutType layoutType) - : GraphLayout({}) +GraphGridLayout::GraphGridLayout(GraphGridLayout::LayoutType layoutType) : GraphLayout({}) { switch (layoutType) { case LayoutType::Narrow: @@ -185,17 +198,13 @@ std::vector GraphGridLayout::topoSort(LayoutState &state, ut64 entry) // * select backwards/loop edges // * perform toposort std::vector blockOrder; - enum class State : uint8_t { - NotVisited = 0, - InStack, - Visited - }; + enum class State : uint8_t { NotVisited = 0, InStack, Visited }; std::unordered_map visited; visited.reserve(state.blocks->size()); std::stack> stack; auto dfsFragment = [&visited, &blocks, &state, &stack, &blockOrder](ut64 first) { visited[first] = State::InStack; - stack.push({first, 0}); + stack.push({ first, 0 }); while (!stack.empty()) { auto v = stack.top().first; auto edge_index = stack.top().second; @@ -206,7 +215,7 @@ std::vector GraphGridLayout::topoSort(LayoutState &state, ut64 entry) auto &targetState = visited[target]; if (targetState == State::NotVisited) { targetState = State::InStack; - stack.push({target, 0}); + stack.push({ target, 0 }); state.grid_blocks[v].dag_edge.push_back(target); } else if (targetState == State::Visited) { state.grid_blocks[v].dag_edge.push_back(target); @@ -232,7 +241,8 @@ std::vector GraphGridLayout::topoSort(LayoutState &state, ut64 entry) return blockOrder; } -void GraphGridLayout::assignRows(GraphGridLayout::LayoutState &state, const std::vector &blockOrder) +void GraphGridLayout::assignRows(GraphGridLayout::LayoutState &state, + const std::vector &blockOrder) { for (auto it = blockOrder.rbegin(), end = blockOrder.rend(); it != end; it++) { auto &block = state.grid_blocks[*it]; @@ -258,7 +268,8 @@ void GraphGridLayout::selectTree(GraphGridLayout::LayoutState &state) } } -void GraphGridLayout::CalculateLayout(GraphLayout::Graph &blocks, ut64 entry, int &width, int &height) const +void GraphGridLayout::CalculateLayout(GraphLayout::Graph &blocks, ut64 entry, int &width, + int &height) const { LayoutState layoutState; layoutState.blocks = &blocks; @@ -307,12 +318,12 @@ void GraphGridLayout::CalculateLayout(GraphLayout::Graph &blocks, ut64 entry, in layoutState.columnWidth.assign(layoutState.columns, 0); for (auto &node : layoutState.grid_blocks) { const auto &inputBlock = blocks[node.first]; - layoutState.rowHeight[node.second.row] = std::max(inputBlock.height, - layoutState.rowHeight[node.second.row]); - layoutState.columnWidth[node.second.col] = std::max(inputBlock.width / 2, - layoutState.columnWidth[node.second.col]); - layoutState.columnWidth[node.second.col + 1] = std::max(inputBlock.width / 2, - layoutState.columnWidth[node.second.col + 1]); + layoutState.rowHeight[node.second.row] = + std::max(inputBlock.height, layoutState.rowHeight[node.second.row]); + layoutState.columnWidth[node.second.col] = + std::max(inputBlock.width / 2, layoutState.columnWidth[node.second.col]); + layoutState.columnWidth[node.second.col + 1] = + std::max(inputBlock.width / 2, layoutState.columnWidth[node.second.col + 1]); } routeEdges(layoutState); @@ -362,8 +373,8 @@ void GraphGridLayout::findMergePoints(GraphGridLayout::LayoutState &state) const } if (blocksGoingToMerge) { block.mergeBlock = mergeBlock->id; - state.grid_blocks[block.tree_edge[blockWithTreeEdge]].col = blockWithTreeEdge * 2 - - (blocksGoingToMerge - 1); + state.grid_blocks[block.tree_edge[blockWithTreeEdge]].col = + blockWithTreeEdge * 2 - (blocksGoingToMerge - 1); } } } @@ -375,12 +386,13 @@ void GraphGridLayout::computeAllBlockPlacement(const std::vector &blockOrd selectTree(layoutState); findMergePoints(layoutState); - - // Shapes of subtrees are maintained using linked lists. Each value within list is column relative to previous row. - // This allows moving things around by changing only first value in list. + // Shapes of subtrees are maintained using linked lists. Each value within list is column + // relative to previous row. This allows moving things around by changing only first value in + // list. LinkedListPool sides(blockOrder.size() * 2); // *2 = two sides for each node - // Process nodes in the order from bottom to top. Ensures that all subtrees are processed before parent node. + // Process nodes in the order from bottom to top. Ensures that all subtrees are processed before + // parent node. for (auto blockId : blockOrder) { auto &block = layoutState.grid_blocks[blockId]; if (block.tree_edge.size() == 0) { @@ -395,7 +407,9 @@ void GraphGridLayout::computeAllBlockPlacement(const std::vector &blockOrd block.rightSideShape = sides.makeList(2); } else { auto &firstChild = layoutState.grid_blocks[block.tree_edge[0]]; - auto leftSide = firstChild.leftSideShape; // left side of block children subtrees processed so far + auto leftSide = + firstChild + .leftSideShape; // left side of block children subtrees processed so far auto rightSide = firstChild.rightSideShape; block.row_count = firstChild.row_count; block.lastRowRight = firstChild.lastRowRight; @@ -413,7 +427,8 @@ void GraphGridLayout::computeAllBlockPlacement(const std::vector &blockOrd int maxLeftWidth = 0; int minRightPos = child.col; - while (leftIt && rightIt) { // process part of subtrees that touch when put side by side + while (leftIt + && rightIt) { // process part of subtrees that touch when put side by side leftPos += *leftIt; rightPos += *rightIt; minPos = std::max(minPos, leftPos - rightPos); @@ -432,16 +447,17 @@ void GraphGridLayout::computeAllBlockPlacement(const std::vector &blockOrd } else { rightTreeOffset = block.rightPosition - minRightPos; } - } // Calculate the new shape after putting the two subtrees side by side child.col += rightTreeOffset; if (leftIt) { *leftIt -= (rightTreeOffset + child.lastRowRight - leftPos); - rightSide = sides.append(child.rightSideShape, sides.splitTail(rightSide, leftIt)); + rightSide = + sides.append(child.rightSideShape, sides.splitTail(rightSide, leftIt)); } else if (rightIt) { *rightIt += (rightPos + rightTreeOffset - block.lastRowLeft); - leftSide = sides.append(leftSide, sides.splitTail(child.leftSideShape, rightIt)); + leftSide = + sides.append(leftSide, sides.splitTail(child.leftSideShape, rightIt)); rightSide = child.rightSideShape; block.lastRowRight = child.lastRowRight + rightTreeOffset; @@ -451,8 +467,10 @@ void GraphGridLayout::computeAllBlockPlacement(const std::vector &blockOrd } *sides.head(rightSide) += rightTreeOffset; block.row_count = std::max(block.row_count, child.row_count); - block.leftPosition = std::min(block.leftPosition, child.leftPosition + rightTreeOffset); - block.rightPosition = std::max(block.rightPosition, rightTreeOffset + child.rightPosition); + block.leftPosition = + std::min(block.leftPosition, child.leftPosition + rightTreeOffset); + block.rightPosition = + std::max(block.rightPosition, rightTreeOffset + child.rightPosition); } int col = 0; @@ -464,8 +482,9 @@ void GraphGridLayout::computeAllBlockPlacement(const std::vector &blockOrd } col /= block.tree_edge.size(); } else { - // mode b) somewhere between left most direct child and right most, preferably in the middle of - // horizontal dimensions. Results layout looks more like single vertical line. + // mode b) somewhere between left most direct child and right most, preferably in + // the middle of horizontal dimensions. Results layout looks more like single + // vertical line. col = (block.rightPosition + block.leftPosition) / 2 - 1; col = std::max(col, layoutState.grid_blocks[block.tree_edge.front()].col - 1); col = std::min(col, layoutState.grid_blocks[block.tree_edge.back()].col + 1); @@ -489,9 +508,9 @@ void GraphGridLayout::computeAllBlockPlacement(const std::vector &blockOrd } } - // Calculate root positions. Typical function should have one root node that matches with entrypoint. - // There can be more of them in case of switch statement analysis failure, unreahable basic blocks or - // using the algorithm for non control flow graphs. + // Calculate root positions. Typical function should have one root node that matches with + // entrypoint. There can be more of them in case of switch statement analysis failure, + // unreahable basic blocks or using the algorithm for non control flow graphs. int nextEmptyColumn = 0; for (auto &blockIt : layoutState.grid_blocks) { auto &block = blockIt.second; @@ -522,23 +541,22 @@ void GraphGridLayout::routeEdges(GraphGridLayout::LayoutState &state) const void GraphGridLayout::calculateEdgeMainColumn(GraphGridLayout::LayoutState &state) const { // Find an empty column as close as possible to start or end block's column. - // Use sweep line approach processing events sorted by row top to bottom. Use an appropriate tree structure - // to contain blocks above sweep line and query for nearest column which isn't blocked by a block. + // Use sweep line approach processing events sorted by row top to bottom. Use an appropriate + // tree structure to contain blocks above sweep line and query for nearest column which isn't + // blocked by a block. - struct Event { + struct Event + { size_t blockId; size_t edgeId; int row; - enum Type { - Edge = 0, - Block = 1 - } type; + enum Type { Edge = 0, Block = 1 } type; }; // create events std::vector events; events.reserve(state.grid_blocks.size() * 2); for (const auto &it : state.grid_blocks) { - events.push_back({it.first, 0, it.second.row, Event::Block}); + events.push_back({ it.first, 0, it.second.row, Event::Block }); const auto &inputBlock = (*state.blocks)[it.first]; int startRow = it.second.row + 1; @@ -549,7 +567,7 @@ void GraphGridLayout::calculateEdgeMainColumn(GraphGridLayout::LayoutState &stat gridEdges[i].dest = targetId; const auto &targetGridBlock = state.grid_blocks[targetId]; int endRow = targetGridBlock.row; - events.push_back({it.first, i, std::max(startRow, endRow), Event::Edge}); + events.push_back({ it.first, i, std::max(startRow, endRow), Event::Edge }); } } std::sort(events.begin(), events.end(), [](const Event &a, const Event &b) { @@ -576,7 +594,8 @@ void GraphGridLayout::calculateEdgeMainColumn(GraphGridLayout::LayoutState &stat // Prefer using the same column as starting node, it allows reducing amount of segments. if (blockedColumns.valueAtPoint(column) < topRow) { edge.mainColumn = column; - } else if (blockedColumns.valueAtPoint(targetColumn) < topRow) { // next try target block column + } else if (blockedColumns.valueAtPoint(targetColumn) + < topRow) { // next try target block column edge.mainColumn = targetColumn; } else { auto nearestLeft = blockedColumns.rightMostLessThan(column, topRow); @@ -584,19 +603,21 @@ void GraphGridLayout::calculateEdgeMainColumn(GraphGridLayout::LayoutState &stat // There should always be empty column at the sides of drawing assert(nearestLeft != -1 && nearestRight != -1); - // Choose closest column. Take into account distance to source and target block columns. + // Choose closest column. Take into account distance to source and target block + // columns. auto distanceLeft = column - nearestLeft + abs(targetColumn - nearestLeft); auto distanceRight = nearestRight - column + abs(targetColumn - nearestRight); // For upward edges try to make a loop instead of 8 shape, // it is slightly longer but produces less crossing. if (targetBlock.row < block.row) { - if (targetColumn < column && blockedColumns.valueAtPoint(column + 1) < topRow && - column - targetColumn <= distanceLeft + 2) { + if (targetColumn < column && blockedColumns.valueAtPoint(column + 1) < topRow + && column - targetColumn <= distanceLeft + 2) { edge.mainColumn = column + 1; continue; - } else if (targetColumn > column && blockedColumns.valueAtPoint(column - 1) < topRow && - targetColumn - column <= distanceRight + 2) { + } else if (targetColumn > column + && blockedColumns.valueAtPoint(column - 1) < topRow + && targetColumn - column <= distanceRight + 2) { edge.mainColumn = column - 1; continue; } @@ -605,9 +626,11 @@ void GraphGridLayout::calculateEdgeMainColumn(GraphGridLayout::LayoutState &stat if (distanceLeft != distanceRight) { edge.mainColumn = distanceLeft < distanceRight ? nearestLeft : nearestRight; } else { - // In case of tie choose based on edge index. Should result in true branches being mostly on one - // side, false branches on other side. - edge.mainColumn = event.edgeId < state.edge[event.blockId].size() / 2 ? nearestLeft : nearestRight; + // In case of tie choose based on edge index. Should result in true branches + // being mostly on one side, false branches on other side. + edge.mainColumn = event.edgeId < state.edge[event.blockId].size() / 2 + ? nearestLeft + : nearestRight; } } } @@ -636,7 +659,8 @@ void GraphGridLayout::roughRouting(GraphGridLayout::LayoutState &state) const edge.addPoint(start.row + 1, start.col + 1); if (edge.mainColumn != start.col + 1) { - edge.addPoint(start.row + 1, start.col + 1, edge.mainColumn < start.col + 1 ? -1 : 1); + edge.addPoint(start.row + 1, start.col + 1, + edge.mainColumn < start.col + 1 ? -1 : 1); edge.addPoint(start.row + 1, edge.mainColumn, target.row <= start.row ? -2 : 0); } int mainColumnKind = 0; @@ -652,13 +676,15 @@ void GraphGridLayout::roughRouting(GraphGridLayout::LayoutState &state) const edge.addPoint(target.row, edge.mainColumn, mainColumnKind); if (target.col + 1 != edge.mainColumn) { edge.addPoint(target.row, target.col + 1, target.row <= start.row ? 2 : 0); - edge.addPoint(target.row, target.col + 1, target.col + 1 < edge.mainColumn ? 1 : -1); + edge.addPoint(target.row, target.col + 1, + target.col + 1 < edge.mainColumn ? 1 : -1); } // reduce edge spacing when there is large amount of edges connected to single block - auto startSpacingOverride = getSpacingOverride((*state.blocks)[start.id].width, start.outputCount); - auto targetSpacingOverride = getSpacingOverride((*state.blocks)[target.id].width, - target.inputCount); + auto startSpacingOverride = + getSpacingOverride((*state.blocks)[start.id].width, start.outputCount); + auto targetSpacingOverride = + getSpacingOverride((*state.blocks)[target.id].width, target.inputCount); edge.points.front().spacingOverride = startSpacingOverride; edge.points.back().spacingOverride = targetSpacingOverride; if (edge.points.size() <= 2) { @@ -669,11 +695,10 @@ void GraphGridLayout::roughRouting(GraphGridLayout::LayoutState &state) const edge.points[1].spacingOverride = startSpacingOverride; } - int length = 0; for (size_t i = 1; i < edge.points.size(); i++) { - length += abs(edge.points[i].row - edge.points[i - 1].row) + - abs(edge.points[i].col - edge.points[i - 1].col); + length += abs(edge.points[i].row - edge.points[i - 1].row) + + abs(edge.points[i].col - edge.points[i - 1].col); } edge.secondaryPriority = 2 * length + (target.row >= start.row ? 1 : 0); } @@ -682,10 +707,11 @@ void GraphGridLayout::roughRouting(GraphGridLayout::LayoutState &state) const namespace { /** - * @brief Single segment of an edge. An edge can be drawn using multiple horizontal and vertical segments. - * x y meaning matches vertical segments. For horizontal segments axis are swapped. + * @brief Single segment of an edge. An edge can be drawn using multiple horizontal and vertical + * segments. x y meaning matches vertical segments. For horizontal segments axis are swapped. */ -struct EdgeSegment { +struct EdgeSegment +{ int y0; int y1; int x; @@ -694,7 +720,8 @@ struct EdgeSegment { int16_t kind; int16_t spacingOverride; //< segment spacing override, 0 if default spacing should be used }; -struct NodeSide { +struct NodeSide +{ int x; int y0; int y1; @@ -705,28 +732,27 @@ struct NodeSide { /** * @brief Calculate segment offsets relative to their column * - * Argument naming uses terms for vertical segments, but the function can be used for horizontal segments as well. + * Argument naming uses terms for vertical segments, but the function can be used for horizontal + * segments as well. * * @param segments Segments that need to be processed. * @param edgeOffsets Output argument for returning segment offsets relative to their columns. - * @param edgeColumnWidth InOut argument describing how much column with edges take. Initial value used as minimal - * value. May be increased to depending on amount of segments in each column and how tightly they are packed. - * @param nodeRightSide Right side of nodes. Used to reduce space reserved for edges by placing them between nodes. + * @param edgeColumnWidth InOut argument describing how much column with edges take. Initial value + * used as minimal value. May be increased to depending on amount of segments in each column and how + * tightly they are packed. + * @param nodeRightSide Right side of nodes. Used to reduce space reserved for edges by placing them + * between nodes. * @param nodeLeftSide Same as right side. * @param columnWidth * @param H All the segmement and node coordinates y0 and y1 are expected to be in range [0;H) - * @param segmentSpacing The expected spacing between two segments in the same column. Actual spacing may be smaller - * for nodes with many edges. + * @param segmentSpacing The expected spacing between two segments in the same column. Actual + * spacing may be smaller for nodes with many edges. */ -void calculateSegmentOffsets( - std::vector &segments, - std::vector &edgeOffsets, - std::vector &edgeColumnWidth, - std::vector &nodeRightSide, - std::vector &nodeLeftSide, - const std::vector &columnWidth, - size_t H, - int segmentSpacing) +void calculateSegmentOffsets(std::vector &segments, std::vector &edgeOffsets, + std::vector &edgeColumnWidth, + std::vector &nodeRightSide, + std::vector &nodeLeftSide, + const std::vector &columnWidth, size_t H, int segmentSpacing) { for (auto &segment : segments) { if (segment.y0 > segment.y1) { @@ -734,9 +760,11 @@ void calculateSegmentOffsets( } } - std::sort(segments.begin(), segments.end(), [](const EdgeSegment & a, const EdgeSegment & b) { - if (a.x != b.x) return a.x < b.x; - if (a.kind != b.kind) return a.kind < b.kind; + std::sort(segments.begin(), segments.end(), [](const EdgeSegment &a, const EdgeSegment &b) { + if (a.x != b.x) + return a.x < b.x; + if (a.kind != b.kind) + return a.kind < b.kind; auto aSize = a.y1 - a.y0; auto bSize = b.y1 - b.y0; if (aSize != bSize) { @@ -754,9 +782,7 @@ void calculateSegmentOffsets( return false; }); - auto compareNode = [](const NodeSide & a, const NodeSide & b) { - return a.x < b.x; - }; + auto compareNode = [](const NodeSide &a, const NodeSide &b) { return a.x < b.x; }; sort(nodeRightSide.begin(), nodeRightSide.end(), compareNode); sort(nodeLeftSide.begin(), nodeLeftSide.end(), compareNode); @@ -776,11 +802,13 @@ void calculateSegmentOffsets( rightSideIt++; } while (rightSideIt != nodeRightSide.end() && rightSideIt->x + 1 == x) { - maxSegment.setRange(rightSideIt->y0, rightSideIt->y1 + 1, rightSideIt->size - leftColumWidth); + maxSegment.setRange(rightSideIt->y0, rightSideIt->y1 + 1, + rightSideIt->size - leftColumWidth); rightSideIt++; } - while (nextSegmentIt != segments.end() && nextSegmentIt->x == x && nextSegmentIt->kind <= 1) { + while (nextSegmentIt != segments.end() && nextSegmentIt->x == x + && nextSegmentIt->kind <= 1) { int y = maxSegment.rangeMaximum(nextSegmentIt->y0, nextSegmentIt->y1 + 1); if (nextSegmentIt->kind != -2) { y = std::max(y, 0); @@ -804,7 +832,8 @@ void calculateSegmentOffsets( leftSideIt++; } while (leftSideIt != nodeLeftSide.end() && leftSideIt->x == x) { - maxSegment.setRange(leftSideIt->y0, leftSideIt->y1 + 1, leftSideIt->size - rightColumnWidth); + maxSegment.setRange(leftSideIt->y0, leftSideIt->y1 + 1, + leftSideIt->size - rightColumnWidth); leftSideIt++; } while (nextSegmentIt != segments.end() && nextSegmentIt->x == x) { @@ -815,33 +844,33 @@ void calculateSegmentOffsets( nextSegmentIt++; } auto rightSideMiddle = std::max(maxSegment.rangeMaximum(0, H), 0); - rightSideMiddle = std::max(rightSideMiddle, edgeColumnWidth[x] - middleWidth - segmentSpacing); + rightSideMiddle = + std::max(rightSideMiddle, edgeColumnWidth[x] - middleWidth - segmentSpacing); for (auto it = firstRightSideSegment; it != nextSegmentIt; ++it) { - edgeOffsets[it->edgeIndex] = middleWidth + (rightSideMiddle - edgeOffsets[it->edgeIndex]) + - segmentSpacing; + edgeOffsets[it->edgeIndex] = + middleWidth + (rightSideMiddle - edgeOffsets[it->edgeIndex]) + segmentSpacing; } edgeColumnWidth[x] = middleWidth + segmentSpacing + rightSideMiddle; } } - /** * @brief Center the segments to the middle of edge columns when possible. * @param segmentOffsets offsets relative to the left side edge column. * @param edgeColumnWidth widths of edge columns * @param segments either all horizontal or all vertical edge segments */ -static void centerEdges( - std::vector &segmentOffsets, - const std::vector &edgeColumnWidth, - const std::vector &segments) +static void centerEdges(std::vector &segmentOffsets, const std::vector &edgeColumnWidth, + const std::vector &segments) { - /* Split segments in each edge column into non intersecting chunks. Center each chunk separately. + /* Split segments in each edge column into non intersecting chunks. Center each chunk + * separately. * - * Process segment endpoints sorted by x and y. Maintain count of currently started segments. When number of - * active segments reaches 0 there is empty space between chunks. + * Process segment endpoints sorted by x and y. Maintain count of currently started segments. + * When number of active segments reaches 0 there is empty space between chunks. */ - struct Event { + struct Event + { int x; int y; int index; @@ -851,18 +880,20 @@ static void centerEdges( events.reserve(segments.size() * 2); for (const auto &segment : segments) { auto offset = segmentOffsets[segment.edgeIndex]; - // Exclude segments which are outside edge column and between the blocks. It's hard to ensure that moving - // them doesn't cause overlap with blocks. + // Exclude segments which are outside edge column and between the blocks. It's hard to + // ensure that moving them doesn't cause overlap with blocks. if (offset >= 0 && offset <= edgeColumnWidth[segment.x]) { - events.push_back({segment.x, segment.y0, segment.edgeIndex, true}); - events.push_back({segment.x, segment.y1, segment.edgeIndex, false}); + events.push_back({ segment.x, segment.y0, segment.edgeIndex, true }); + events.push_back({ segment.x, segment.y1, segment.edgeIndex, false }); } } - std::sort(events.begin(), events.end(), [](const Event & a, const Event & b) { - if (a.x != b.x) return a.x < b.x; - if (a.y != b.y) return a.y < b.y; - // Process segment start events before end to ensure that activeSegmentCount doesn't go negative and only - // reaches 0 at the end of chunk. + std::sort(events.begin(), events.end(), [](const Event &a, const Event &b) { + if (a.x != b.x) + return a.x < b.x; + if (a.y != b.y) + return a.y < b.y; + // Process segment start events before end to ensure that activeSegmentCount doesn't go + // negative and only reaches 0 at the end of chunk. return int(a.start) > int(b.start); }); @@ -896,8 +927,7 @@ static void centerEdges( * @param rightSides * @return Size of compressed coordinate range. */ -static int compressCoordinates(std::vector &segments, - std::vector &leftSides, +static int compressCoordinates(std::vector &segments, std::vector &leftSides, std::vector &rightSides) { std::vector positions; @@ -916,8 +946,9 @@ static int compressCoordinates(std::vector &segments, auto lastUnique = std::unique(positions.begin(), positions.end()); positions.erase(lastUnique, positions.end()); - auto positionToIndex = [&] (int position) { - size_t index = std::lower_bound(positions.begin(), positions.end(), position) - positions.begin(); + auto positionToIndex = [&](int position) { + size_t index = + std::lower_bound(positions.begin(), positions.end(), position) - positions.begin(); assert(index < positions.size()); return index; }; @@ -937,8 +968,8 @@ void GraphGridLayout::elaborateEdgePlacement(GraphGridLayout::LayoutState &state { int edgeIndex = 0; - auto segmentFromPoint = - [&edgeIndex](const Point & point, const GridEdge & edge, int y0, int y1, int x) { + auto segmentFromPoint = [&edgeIndex](const Point &point, const GridEdge &edge, int y0, int y1, + int x) { EdgeSegment segment; segment.y0 = y0; segment.y1 = y1; @@ -950,7 +981,6 @@ void GraphGridLayout::elaborateEdgePlacement(GraphGridLayout::LayoutState &state return segment; }; - std::vector segments; std::vector rightSides; std::vector leftSides; @@ -960,10 +990,10 @@ void GraphGridLayout::elaborateEdgePlacement(GraphGridLayout::LayoutState &state for (auto &edgeListIt : state.edge) { for (const auto &edge : edgeListIt.second) { for (size_t j = 1; j < edge.points.size(); j += 2) { - segments.push_back(segmentFromPoint(edge.points[j], edge, - edge.points[j-1].row * 2, // edges in even rows - edge.points[j].row * 2, - edge.points[j].col)); + segments.push_back( + segmentFromPoint(edge.points[j], edge, + edge.points[j - 1].row * 2, // edges in even rows + edge.points[j].row * 2, edge.points[j].col)); } } } @@ -974,14 +1004,15 @@ void GraphGridLayout::elaborateEdgePlacement(GraphGridLayout::LayoutState &state // not the same as leftWidth, you would think that one pixel offset isn't visible, but it is auto rightWidth = width - leftWidth; int row = node.row * 2 + 1; // blocks in odd rows - leftSides.push_back({node.col, row, row, leftWidth}); - rightSides.push_back({node.col + 1, row, row, rightWidth}); + leftSides.push_back({ node.col, row, row, leftWidth }); + rightSides.push_back({ node.col + 1, row, row, rightWidth }); } state.edgeColumnWidth.assign(state.columns + 1, layoutConfig.blockHorizontalSpacing); state.edgeColumnWidth[0] = state.edgeColumnWidth.back() = layoutConfig.edgeHorizontalSpacing; edgeOffsets.resize(edgeIndex); calculateSegmentOffsets(segments, edgeOffsets, state.edgeColumnWidth, rightSides, leftSides, - state.columnWidth, 2 * state.rows + 1, layoutConfig.edgeHorizontalSpacing); + state.columnWidth, 2 * state.rows + 1, + layoutConfig.edgeHorizontalSpacing); centerEdges(edgeOffsets, state.edgeColumnWidth, segments); edgeIndex = 0; @@ -1001,8 +1032,10 @@ void GraphGridLayout::elaborateEdgePlacement(GraphGridLayout::LayoutState &state if (block) { int blockWidth = block->width; int edgeColumWidth = state.edgeColumnWidth[edge.points[j].col]; - offset = std::max(-blockWidth / 2 + edgeColumWidth/ 2, offset); - offset = std::min(edgeColumWidth / 2 + std::min(blockWidth, edgeColumWidth) / 2, offset); + offset = std::max(-blockWidth / 2 + edgeColumWidth / 2, offset); + offset = std::min(edgeColumWidth / 2 + + std::min(blockWidth, edgeColumWidth) / 2, + offset); } } edge.points[j].offset = offset; @@ -1015,18 +1048,17 @@ void GraphGridLayout::elaborateEdgePlacement(GraphGridLayout::LayoutState &state for (auto &segment : segments) { auto &offset = edgeOffsets[segment.edgeIndex]; if (segment.kind == -2) { - offset -= (state.edgeColumnWidth[segment.x - 1] / 2 + state.columnWidth[segment.x - 1]) - - oldColumnWidths[segment.x - 1]; + offset -= (state.edgeColumnWidth[segment.x - 1] / 2 + state.columnWidth[segment.x - 1]) + - oldColumnWidths[segment.x - 1]; } else if (segment.kind == 2) { - offset += (state.edgeColumnWidth[segment.x + 1] / 2 + state.columnWidth[segment.x]) - - oldColumnWidths[segment.x]; + offset += (state.edgeColumnWidth[segment.x + 1] / 2 + state.columnWidth[segment.x]) + - oldColumnWidths[segment.x]; } } - calculateColumnOffsets(state.columnWidth, state.edgeColumnWidth, - state.columnOffset, state.edgeColumnOffset); + calculateColumnOffsets(state.columnWidth, state.edgeColumnWidth, state.columnOffset, + state.edgeColumnOffset); copySegmentsToEdges(true); - // Horizontal segments // Use exact x coordinates obtained from vertical segment placement. segments.clear(); @@ -1039,7 +1071,8 @@ void GraphGridLayout::elaborateEdgePlacement(GraphGridLayout::LayoutState &state for (size_t j = 2; j < edge.points.size(); j += 2) { int y0 = state.edgeColumnOffset[edge.points[j - 1].col] + edge.points[j - 1].offset; int y1 = state.edgeColumnOffset[edge.points[j + 1].col] + edge.points[j + 1].offset; - segments.push_back(segmentFromPoint(edge.points[j], edge, y0, y1, edge.points[j].row)); + segments.push_back( + segmentFromPoint(edge.points[j], edge, y0, y1, edge.points[j].row)); } } } @@ -1047,8 +1080,8 @@ void GraphGridLayout::elaborateEdgePlacement(GraphGridLayout::LayoutState &state for (auto &blockIt : state.grid_blocks) { auto &node = blockIt.second; auto blockWidth = (*state.blocks)[node.id].width; - int leftSide = state.edgeColumnOffset[node.col + 1] + state.edgeColumnWidth[node.col + 1] / 2 - - blockWidth / 2; + int leftSide = state.edgeColumnOffset[node.col + 1] + + state.edgeColumnWidth[node.col + 1] / 2 - blockWidth / 2; int rightSide = leftSide + blockWidth; int h = (*state.blocks)[blockIt.first].height; @@ -1059,15 +1092,16 @@ void GraphGridLayout::elaborateEdgePlacement(GraphGridLayout::LayoutState &state topProfile -= freeSpace / 2; bottomProfile += freeSpace / 2; } - leftSides.push_back({node.row, leftSide, rightSide, topProfile}); - rightSides.push_back({node.row, leftSide, rightSide, bottomProfile}); + leftSides.push_back({ node.row, leftSide, rightSide, topProfile }); + rightSides.push_back({ node.row, leftSide, rightSide, bottomProfile }); } state.edgeRowHeight.assign(state.rows + 1, layoutConfig.blockVerticalSpacing); state.edgeRowHeight[0] = state.edgeRowHeight.back() = layoutConfig.edgeVerticalSpacing; edgeOffsets.resize(edgeIndex); auto compressedCoordinates = compressCoordinates(segments, leftSides, rightSides); calculateSegmentOffsets(segments, edgeOffsets, state.edgeRowHeight, rightSides, leftSides, - state.rowHeight, compressedCoordinates, layoutConfig.edgeVerticalSpacing); + state.rowHeight, compressedCoordinates, + layoutConfig.edgeVerticalSpacing); copySegmentsToEdges(false); } @@ -1077,17 +1111,20 @@ void GraphGridLayout::adjustColumnWidths(GraphGridLayout::LayoutState &state) co state.columnWidth.assign(state.columns, 0); for (auto &node : state.grid_blocks) { const auto &inputBlock = (*state.blocks)[node.first]; - state.rowHeight[node.second.row] = std::max(inputBlock.height, state.rowHeight[node.second.row]); + state.rowHeight[node.second.row] = + std::max(inputBlock.height, state.rowHeight[node.second.row]); int edgeWidth = state.edgeColumnWidth[node.second.col + 1]; int columnWidth = (inputBlock.width - edgeWidth) / 2; - state.columnWidth[node.second.col] = std::max(columnWidth, state.columnWidth[node.second.col]); - state.columnWidth[node.second.col + 1] = std::max(columnWidth, - state.columnWidth[node.second.col + 1]); + state.columnWidth[node.second.col] = + std::max(columnWidth, state.columnWidth[node.second.col]); + state.columnWidth[node.second.col + 1] = + std::max(columnWidth, state.columnWidth[node.second.col + 1]); } } int GraphGridLayout::calculateColumnOffsets(const std::vector &columnWidth, - std::vector &edgeColumnWidth, std::vector &columnOffset, + std::vector &edgeColumnWidth, + std::vector &columnOffset, std::vector &edgeColumnOffset) { assert(edgeColumnWidth.size() == columnWidth.size() + 1); @@ -1105,23 +1142,21 @@ int GraphGridLayout::calculateColumnOffsets(const std::vector &columnWidth, return position; } -void GraphGridLayout::convertToPixelCoordinates( - GraphGridLayout::LayoutState &state, - int &width, - int &height) const +void GraphGridLayout::convertToPixelCoordinates(GraphGridLayout::LayoutState &state, int &width, + int &height) const { // calculate row and column offsets - width = calculateColumnOffsets(state.columnWidth, state.edgeColumnWidth, - state.columnOffset, state.edgeColumnOffset); - height = calculateColumnOffsets(state.rowHeight, state.edgeRowHeight, - state.rowOffset, state.edgeRowOffset); + width = calculateColumnOffsets(state.columnWidth, state.edgeColumnWidth, state.columnOffset, + state.edgeColumnOffset); + height = calculateColumnOffsets(state.rowHeight, state.edgeRowHeight, state.rowOffset, + state.edgeRowOffset); // block pixel positions for (auto &block : (*state.blocks)) { const auto &gridBlock = state.grid_blocks[block.first]; - block.second.x = state.edgeColumnOffset[gridBlock.col + 1] + - state.edgeColumnWidth[gridBlock.col + 1] / 2 - block.second.width / 2; + block.second.x = state.edgeColumnOffset[gridBlock.col + 1] + + state.edgeColumnWidth[gridBlock.col + 1] / 2 - block.second.width / 2; block.second.y = state.rowOffset[gridBlock.row]; if (verticalBlockAlignmentMiddle) { block.second.y += (state.rowHeight[gridBlock.row] - block.second.height) / 2; @@ -1162,14 +1197,14 @@ void GraphGridLayout::cropToContent(GraphLayout::Graph &graph, int &width, int & return; } const auto &anyBlock = graph.begin()->second; - int minPos[2] = {anyBlock.x, anyBlock.y}; - int maxPos[2] = {anyBlock.x, anyBlock.y}; + int minPos[2] = { anyBlock.x, anyBlock.y }; + int maxPos[2] = { anyBlock.x, anyBlock.y }; auto updateLimits = [&](int x, int y) { - minPos[0] = std::min(minPos[0] , x); - minPos[1] = std::min(minPos[1] , y); - maxPos[0] = std::max(maxPos[0] , x); - maxPos[1] = std::max(maxPos[1] , y); + minPos[0] = std::min(minPos[0], x); + minPos[1] = std::min(minPos[1], y); + maxPos[0] = std::max(maxPos[0], x); + maxPos[1] = std::max(maxPos[1], y); }; for (const auto &blockIt : graph) { @@ -1177,7 +1212,7 @@ void GraphGridLayout::cropToContent(GraphLayout::Graph &graph, int &width, int & updateLimits(block.x, block.y); updateLimits(block.x + block.width, block.y + block.height); for (auto &edge : block.edges) { - for (auto &point: edge.polyline) { + for (auto &point : edge.polyline) { updateLimits(point.x(), point.y()); } } @@ -1191,7 +1226,7 @@ void GraphGridLayout::cropToContent(GraphLayout::Graph &graph, int &width, int & block.x -= minPos[0]; block.y -= minPos[1]; for (auto &edge : block.edges) { - for (auto &point: edge.polyline) { + for (auto &point : edge.polyline) { point -= QPointF(minPos[0], minPos[1]); } } @@ -1223,16 +1258,14 @@ using Constraint = std::pair, int>; * @param objectiveFunction coefficients for function \f$\sum c_i x_i\f$ which needs to be minimized * @param inequalities inequality constraints \f$x_{e_i} - x_{f_i} \leq b_i\f$ * @param equalities equality constraints \f$x_{e_i} - x_{f_i} = b_i\f$ - * @param solution input/output argument, returns results, needs to be initialized with a feasible solution + * @param solution input/output argument, returns results, needs to be initialized with a feasible + * solution * @param stickWhenNotMoving variable grouping strategy */ -static void optimizeLinearProgramPass( - size_t n, - std::vector objectiveFunction, - std::vector inequalities, - std::vector equalities, - std::vector &solution, - bool stickWhenNotMoving) +static void optimizeLinearProgramPass(size_t n, std::vector objectiveFunction, + std::vector inequalities, + std::vector equalities, + std::vector &solution, bool stickWhenNotMoving) { std::vector group(n); std::iota(group.begin(), group.end(), 0); // initially each variable is in it's own group @@ -1251,9 +1284,7 @@ static void optimizeLinearProgramPass( } return v; }; - auto joinGroup = [&](int a, int b) { - group[getGroup(b)] = getGroup(a); - }; + auto joinGroup = [&](int a, int b) { group[getGroup(b)] = getGroup(a); }; for (auto &constraint : inequalities) { int a = constraint.first.first; @@ -1265,8 +1296,8 @@ static void optimizeLinearProgramPass( edgeCount[b]++; } std::vector processed(n); - // Smallest variable value in the group relative to main one, this is used to maintain implicit x_i >= 0 - // constraint + // Smallest variable value in the group relative to main one, this is used to maintain implicit + // x_i >= 0 constraint std::vector groupRelativeMin(n, 0); auto joinSegmentGroups = [&](int a, int b) { @@ -1277,17 +1308,19 @@ static void optimizeLinearProgramPass( objectiveFunction[a] += objectiveFunction[b]; int internalEdgeCount = 0; auto writeIt = edgePool.head(edges[b]); - // update inequalities and remove some of the constraints between variables that are now grouped + // update inequalities and remove some of the constraints between variables that are now + // grouped for (auto it = edgePool.head(edges[b]); it; ++it) { auto &constraint = inequalities[*it]; int other = constraint.first.first + constraint.first.second - b; - if (getGroup(other) == a) { // skip inequalities where both variables are now in the same group + if (getGroup(other) + == a) { // skip inequalities where both variables are now in the same group internalEdgeCount++; continue; } *writeIt++ = *it; - // Modify the inequalities for the group being attached relative to the main variable in the group - // to which it is being attached. + // Modify the inequalities for the group being attached relative to the main variable in + // the group to which it is being attached. int diff = solution[a] - solution[b]; if (b == constraint.first.first) { constraint.first.first = a; @@ -1299,37 +1332,42 @@ static void optimizeLinearProgramPass( } edges[a] = edgePool.append(edges[a], edgePool.splitHead(edges[b], writeIt)); edgeCount[a] -= internalEdgeCount; - groupRelativeMin[a] = std::min(groupRelativeMin[a], groupRelativeMin[b] + solution[b]- solution[a]); + groupRelativeMin[a] = + std::min(groupRelativeMin[a], groupRelativeMin[b] + solution[b] - solution[a]); }; for (auto &equality : equalities) { - // process equalities, assumes that initial solution is feasible solution and matches equality constraints + // process equalities, assumes that initial solution is feasible solution and matches + // equality constraints int a = getGroup(equality.first.first); int b = getGroup(equality.first.second); if (a == b) { - equality = {{0, 0}, 0}; + equality = { { 0, 0 }, 0 }; continue; } // always join smallest group to bigger one if (edgeCount[a] > edgeCount[b]) { std::swap(a, b); - // Update the equality equation so that later variable values can be calculated by simply iterating through - // them without need to check which direction the group joining was done. + // Update the equality equation so that later variable values can be calculated by + // simply iterating through them without need to check which direction the group joining + // was done. std::swap(equality.first.first, equality.first.second); equality.second = -equality.second; } joinSegmentGroups(b, a); - equality = {{a, b}, solution[a] - solution[b]}; + equality = { { a, b }, solution[a] - solution[b] }; processed[a] = 1; } - // Priority queue for processing groups starting with currently smallest one. Doing it this way should result in - // number of constraints within group doubling each time two groups are joined. That way each constraint is - // processed no more than log(n) times. - std::priority_queue, std::vector>, std::greater>> queue; + // Priority queue for processing groups starting with currently smallest one. Doing it this way + // should result in number of constraints within group doubling each time two groups are joined. + // That way each constraint is processed no more than log(n) times. + std::priority_queue, std::vector>, + std::greater>> + queue; for (size_t i = 0; i < n; i++) { if (!processed[i]) { - queue.push({edgeCount[i], i}); + queue.push({ edgeCount[i], i }); } } while (!queue.empty()) { @@ -1343,8 +1381,8 @@ static void optimizeLinearProgramPass( if (direction == 0) { continue; } - // Find the first constraint which will be hit by changing the variable in the desired direction defined - // by objective function. + // Find the first constraint which will be hit by changing the variable in the desired + // direction defined by objective function. int limitingGroup = -1; int smallestMove = 0; if (direction < 0) { @@ -1396,9 +1434,9 @@ static void optimizeLinearProgramPass( if (limitingGroup != -1) { joinSegmentGroups(limitingGroup, g); if (!processed[limitingGroup]) { - queue.push({edgeCount[limitingGroup], limitingGroup}); + queue.push({ edgeCount[limitingGroup], limitingGroup }); } - equalities.push_back({{g, limitingGroup}, solution[g] - solution[limitingGroup]}); + equalities.push_back({ { g, limitingGroup }, solution[g] - solution[limitingGroup] }); } // else do nothing if limited by variable >= 0 } for (auto it = equalities.rbegin(), end = equalities.rend(); it != end; ++it) { @@ -1413,78 +1451,78 @@ static void optimizeLinearProgramPass( * @param objectiveFunction coefficients for function \f$\sum c_i x_i\f$ which needs to be minimized * @param inequalities inequality constraints \f$x_{e_i} - x_{f_i} \leq b_i\f$ * @param equalities equality constraints \f$x_{e_i} - x_{f_i} = b_i\f$ - * @param solution input/output argument, returns results, needs to be initialized with a feasible solution + * @param solution input/output argument, returns results, needs to be initialized with a feasible + * solution */ -static void optimizeLinearProgram( - size_t n, - const std::vector &objectiveFunction, - std::vector inequalities, - const std::vector &equalities, - std::vector &solution) +static void optimizeLinearProgram(size_t n, const std::vector &objectiveFunction, + std::vector inequalities, + const std::vector &equalities, + std::vector &solution) { // Remove redundant inequalities std::sort(inequalities.begin(), inequalities.end()); - auto uniqueEnd = std::unique(inequalities.begin(), inequalities.end(), - [](const Constraint &a, const Constraint &b){ - return a.first == b.first; - }); + auto uniqueEnd = std::unique( + inequalities.begin(), inequalities.end(), + [](const Constraint &a, const Constraint &b) { return a.first == b.first; }); inequalities.erase(uniqueEnd, inequalities.end()); - static const int ITERATIONS = 1; for (int i = 0; i < ITERATIONS; i++) { optimizeLinearProgramPass(n, objectiveFunction, inequalities, equalities, solution, true); - //optimizeLinearProgramPass(n, objectiveFunction, inequalities, equalities, solution, false); + // optimizeLinearProgramPass(n, objectiveFunction, inequalities, equalities, solution, + // false); } } namespace { - struct Segment { - int x; - int variableId; - int y0, y1; - }; +struct Segment +{ + int x; + int variableId; + int y0, y1; +}; } -static Constraint createInequality(size_t a, int posA, size_t b, int posB, int minSpacing, const std::vector &positions) +static Constraint createInequality(size_t a, int posA, size_t b, int posB, int minSpacing, + const std::vector &positions) { minSpacing = std::min(minSpacing, posB - posA); - return {{a, b}, posB - positions[b] - (posA - positions[a]) - minSpacing}; + return { { a, b }, posB - positions[b] - (posA - positions[a]) - minSpacing }; } /** - * @brief Create inequality constraints from segments which preserves their relative order on single axis. + * @brief Create inequality constraints from segments which preserves their relative order on single + * axis. * * @param segments list of edge segments and block sides * @param positions initial element positions before optimization * @param blockCount number of variables representing blocks, it is assumed that segments with * variableId < \a blockCount represent one side of block. - * @param variableGroup used to check if segments are part of the same edge and spacing can be reduced + * @param variableGroup used to check if segments are part of the same edge and spacing can be + * reduced * @param blockSpacing minimal spacing between blocks - * @param segmentSpacing minimal spacing between two edge segments, spacing may be less if values in \a positions - * are closer than this - * @param inequalities output variable for resulting inequalities, values initially stored in it are not removed + * @param segmentSpacing minimal spacing between two edge segments, spacing may be less if values in + * \a positions are closer than this + * @param inequalities output variable for resulting inequalities, values initially stored in it are + * not removed */ -static void createInequalitiesFromSegments( - std::vector segments, - const std::vector& positions, - const std::vector& variableGroup, - int blockCount, - int blockSpacing, - int segmentSpacing, - std::vector &inequalities) +static void createInequalitiesFromSegments(std::vector segments, + const std::vector &positions, + const std::vector &variableGroup, int blockCount, + int blockSpacing, int segmentSpacing, + std::vector &inequalities) { // map used as binary search tree y_position -> segment{variableId, x_position} // It is used to maintain which segment was last seen in the range y_position.. std::map> lastSegments; - lastSegments[-1] = {-1, -1}; + lastSegments[-1] = { -1, -1 }; - std::sort(segments.begin(), segments.end(), [](const Segment &a, const Segment &b) { - return a.x < b.x; - }); + std::sort(segments.begin(), segments.end(), + [](const Segment &a, const Segment &b) { return a.x < b.x; }); for (auto &segment : segments) { auto startPos = lastSegments.lower_bound(segment.y0); - --startPos; // should never be lastSegment.begin() because map is initialized with segment at pos -1 + --startPos; // should never be lastSegment.begin() because map is initialized with segment + // at pos -1 auto lastSegment = startPos->second; auto it = startPos; while (it != lastSegments.end() && it->first <= segment.y1) { @@ -1499,12 +1537,13 @@ static void createInequalitiesFromSegments( continue; } minSpacing = blockSpacing; - } else if (variableGroup[prevSegmentVariable] == variableGroup[segment.variableId]) { + } else if (variableGroup[prevSegmentVariable] + == variableGroup[segment.variableId]) { minSpacing = 0; } inequalities.push_back(createInequality(prevSegmentVariable, prevSegmentPos, - segment.variableId, segment.x, - minSpacing, positions)); + segment.variableId, segment.x, minSpacing, + positions)); } lastSegment = it->second; ++it; @@ -1513,8 +1552,11 @@ static void createInequalitiesFromSegments( startPos++; } lastSegments.erase(startPos, it); // erase segments covered by current one - lastSegments[segment.y0] = {segment.variableId, segment.x}; // current segment - // either current segment splitting previous one into two parts or remaining part of partially covered segment + lastSegments[segment.y0] = { + segment.variableId, segment.x + }; // current segment + // either current segment splitting previous one into two parts or remaining part of + // partially covered segment lastSegments[segment.y1] = lastSegment; } } @@ -1550,7 +1592,7 @@ void GraphGridLayout::optimizeLayout(GraphGridLayout::LayoutState &state) const auto addBlockSegmentEquality = [&](ut64 blockId, int edgeVariable, int edgeVariablePos) { int blockPos = (*state.blocks)[blockId].x; int blockVariable = blockMapping[blockId]; - equalities.push_back({{blockVariable, edgeVariable}, blockPos - edgeVariablePos}); + equalities.push_back({ { blockVariable, edgeVariable }, blockPos - edgeVariablePos }); }; auto setFeasibleSolution = [&](size_t variable, int value) { solution.resize(std::max(solution.size(), variable + 1)); @@ -1587,7 +1629,6 @@ void GraphGridLayout::optimizeLayout(GraphGridLayout::LayoutState &state) const size_t edgeIndex = 0; // horizontal segments - objectiveFunction.assign(blockMapping.size(), 1); for (auto &blockIt : *state.blocks) { auto &block = blockIt.second; @@ -1596,7 +1637,7 @@ void GraphGridLayout::optimizeLayout(GraphGridLayout::LayoutState &state) const auto &targetBlock = (*state.blocks)[edge.target]; if (block.y < targetBlock.y) { int spacing = block.height + layoutConfig.blockVerticalSpacing; - inequalities.push_back({{blockVariable, blockMapping[edge.target]}, -spacing}); + inequalities.push_back({ { blockVariable, blockMapping[edge.target] }, -spacing }); } if (edge.polyline.size() < 3) { continue; @@ -1608,7 +1649,7 @@ void GraphGridLayout::optimizeLayout(GraphGridLayout::LayoutState &state) const std::swap(y0, y1); } int x = edge.polyline[i].y(); - segments.push_back({x, int(variableIndex), y0, y1}); + segments.push_back({ x, int(variableIndex), y0, y1 }); variableGroups.push_back(blockMapping.size() + edgeIndex); setFeasibleSolution(variableIndex, x); if (i > 2) { @@ -1619,13 +1660,15 @@ void GraphGridLayout::optimizeLayout(GraphGridLayout::LayoutState &state) const } edgeIndex++; } - segments.push_back({block.y, blockVariable, block.x, block.x + block.width}); - segments.push_back({block.y + block.height, blockVariable, block.x, block.x + block.width}); + segments.push_back({ block.y, blockVariable, block.x, block.x + block.width }); + segments.push_back( + { block.y + block.height, blockVariable, block.x, block.x + block.width }); setFeasibleSolution(blockVariable, block.y); } - createInequalitiesFromSegments(std::move(segments), solution, variableGroups, blockMapping.size(), - layoutConfig.blockVerticalSpacing, layoutConfig.edgeVerticalSpacing, inequalities); + createInequalitiesFromSegments(std::move(segments), solution, variableGroups, + blockMapping.size(), layoutConfig.blockVerticalSpacing, + layoutConfig.edgeVerticalSpacing, inequalities); objectiveFunction.resize(solution.size()); optimizeLinearProgram(solution.size(), objectiveFunction, inequalities, equalities, solution); @@ -1655,7 +1698,7 @@ void GraphGridLayout::optimizeLayout(GraphGridLayout::LayoutState &state) const std::swap(y0, y1); } int x = edge.polyline[i].x(); - segments.push_back({x, int(variableIndex), y0, y1}); + segments.push_back({ x, int(variableIndex), y0, y1 }); variableGroups.push_back(blockMapping.size() + edgeIndex); setFeasibleSolution(variableIndex, x); if (i > 2) { @@ -1670,13 +1713,15 @@ void GraphGridLayout::optimizeLayout(GraphGridLayout::LayoutState &state) const edgeIndex++; } int blockVariable = blockMapping[blockIt.first]; - segments.push_back({block.x, blockVariable, block.y, block.y + block.height}); - segments.push_back({block.x + block.width, blockVariable, block.y, block.y + block.height}); + segments.push_back({ block.x, blockVariable, block.y, block.y + block.height }); + segments.push_back( + { block.x + block.width, blockVariable, block.y, block.y + block.height }); setFeasibleSolution(blockVariable, block.x); } - createInequalitiesFromSegments(std::move(segments), solution, variableGroups, blockMapping.size(), - layoutConfig.blockHorizontalSpacing, layoutConfig.edgeHorizontalSpacing, inequalities); + createInequalitiesFromSegments(std::move(segments), solution, variableGroups, + blockMapping.size(), layoutConfig.blockHorizontalSpacing, + layoutConfig.edgeHorizontalSpacing, inequalities); objectiveFunction.resize(solution.size()); // horizontal centering constraints @@ -1689,17 +1734,16 @@ void GraphGridLayout::optimizeLayout(GraphGridLayout::LayoutState &state) const auto middle = block.x + block.width / 2; if (blockLeft.x + blockLeft.width < middle && blockRight.x > middle) { addInequality(blockMapping[block.edges[0].target], blockLeft.x + blockLeft.width, - blockVariable, middle, - layoutConfig.blockHorizontalSpacing / 2); - addInequality(blockVariable, middle, - blockMapping[block.edges[1].target], blockRight.x, - layoutConfig.blockHorizontalSpacing / 2); + blockVariable, middle, layoutConfig.blockHorizontalSpacing / 2); + addInequality(blockVariable, middle, blockMapping[block.edges[1].target], + blockRight.x, layoutConfig.blockHorizontalSpacing / 2); auto &gridBlock = state.grid_blocks[blockIt.first]; if (gridBlock.mergeBlock) { auto &mergeBlock = (*state.blocks)[gridBlock.mergeBlock]; if (mergeBlock.x + mergeBlock.width / 2 == middle) { - equalities.push_back({{blockVariable, blockMapping[gridBlock.mergeBlock]}, - block.x - mergeBlock.x}); + equalities.push_back( + { { blockVariable, blockMapping[gridBlock.mergeBlock] }, + block.x - mergeBlock.x }); } } } @@ -1709,4 +1753,3 @@ void GraphGridLayout::optimizeLayout(GraphGridLayout::LayoutState &state) const optimizeLinearProgram(solution.size(), objectiveFunction, inequalities, equalities, solution); copyVariablesToPositions(solution); } - diff --git a/src/widgets/GraphGridLayout.h b/src/widgets/GraphGridLayout.h index d547ee39..84654e96 100644 --- a/src/widgets/GraphGridLayout.h +++ b/src/widgets/GraphGridLayout.h @@ -5,9 +5,9 @@ #include "GraphLayout.h" #include "common/LinkedListPool.h" - /** - * @brief Graph layout algorithm on layered graph layout approach. For simplicity all the nodes are placed in a grid. + * @brief Graph layout algorithm on layered graph layout approach. For simplicity all the nodes are + * placed in a grid. */ class GraphGridLayout : public GraphLayout { @@ -19,14 +19,12 @@ public: }; GraphGridLayout(LayoutType layoutType = LayoutType::Medium); - virtual void CalculateLayout(Graph &blocks, - ut64 entry, - int &width, - int &height) const override; + virtual void CalculateLayout(Graph &blocks, ut64 entry, int &width, int &height) const override; void setTightSubtreePlacement(bool enabled) { tightSubtreePlacement = enabled; } void setParentBetweenDirectChild(bool enabled) { parentBetweenDirectChild = enabled; } void setverticalBlockAlignmentMiddle(bool enabled) { verticalBlockAlignmentMiddle = enabled; } void setLayoutOptimization(bool enabled) { useLayoutOptimization = enabled; } + private: /// false - use bounding box for smallest subtree when placing them side by side bool tightSubtreePlacement = false; @@ -36,7 +34,8 @@ private: bool verticalBlockAlignmentMiddle = false; bool useLayoutOptimization = true; - struct GridBlock { + struct GridBlock + { ut64 id; std::vector tree_edge; //!< subset of outgoing edges that form a tree std::vector dag_edge; //!< subset of outgoing edges that form a dag @@ -61,7 +60,8 @@ private: LinkedListPool::List rightSideShape; }; - struct Point { + struct Point + { int row; int col; int offset; @@ -69,7 +69,8 @@ private: int16_t spacingOverride; }; - struct GridEdge { + struct GridEdge + { ut64 dest; int mainColumn = -1; std::vector points; @@ -77,11 +78,12 @@ private: void addPoint(int row, int col, int16_t kind = 0) { - this->points.push_back({row, col, 0, kind, 0}); + this->points.push_back({ row, col, 0, kind, 0 }); } }; - struct LayoutState { + struct LayoutState + { std::unordered_map grid_blocks; std::unordered_map *blocks = nullptr; std::unordered_map> edge; @@ -102,7 +104,8 @@ private: /** * @brief Find nodes where control flow merges after splitting. - * Sets node column offset so that after computing placement merge point is centered bellow nodes above. + * Sets node column offset so that after computing placement merge point is centered bellow + * nodes above. */ void findMergePoints(LayoutState &state) const; /** @@ -113,8 +116,8 @@ private: LayoutState &layoutState) const; /** * @brief Perform the topological sorting of graph nodes. - * If the graph contains loops, a subset of edges is selected. Subset of edges forming DAG are stored in - * GridBlock::dag_edge. + * If the graph contains loops, a subset of edges is selected. Subset of edges forming DAG are + * stored in GridBlock::dag_edge. * @param state Graph layout state including the input graph. * @param entry Entrypoint node. When removing loops prefer placing this node at top. * @return Reverse topological ordering. @@ -162,10 +165,13 @@ private: * @param edgeColumnOffset * @return total width of all the columns */ - static int calculateColumnOffsets(const std::vector &columnWidth, std::vector &edgeColumnWidth, - std::vector &columnOffset, std::vector &edgeColumnOffset); + static int calculateColumnOffsets(const std::vector &columnWidth, + std::vector &edgeColumnWidth, + std::vector &columnOffset, + std::vector &edgeColumnOffset); /** - * @brief Final graph layout step. Convert grids cell relative positions to absolute pixel positions. + * @brief Final graph layout step. Convert grids cell relative positions to absolute pixel + * positions. * @param state * @param width image width output argument * @param height image height output argument @@ -184,7 +190,8 @@ private: */ void connectEdgeEnds(Graph &graph) const; /** - * @brief Reduce spacing between nodes and edges by pushing everything together ignoring the grid. + * @brief Reduce spacing between nodes and edges by pushing everything together ignoring the + * grid. * @param state */ void optimizeLayout(LayoutState &state) const; diff --git a/src/widgets/GraphHorizontalAdapter.cpp b/src/widgets/GraphHorizontalAdapter.cpp index 929db8e7..cea2853e 100644 --- a/src/widgets/GraphHorizontalAdapter.cpp +++ b/src/widgets/GraphHorizontalAdapter.cpp @@ -1,22 +1,19 @@ #include "GraphHorizontalAdapter.h" GraphHorizontalAdapter::GraphHorizontalAdapter(std::unique_ptr layout) - : GraphLayout({}) - , layout(std::move(layout)) + : GraphLayout({}), layout(std::move(layout)) { swapLayoutConfigDirection(); } -void GraphHorizontalAdapter::CalculateLayout( - GraphLayout::Graph &blocks, - unsigned long long entry, - int &width, - int &height) const +void GraphHorizontalAdapter::CalculateLayout(GraphLayout::Graph &blocks, unsigned long long entry, + int &width, int &height) const { for (auto &block : blocks) { std::swap(block.second.width, block.second.height); } - layout->CalculateLayout(blocks, entry, height, width); // intentionally swapping height and width + layout->CalculateLayout(blocks, entry, height, + width); // intentionally swapping height and width for (auto &block : blocks) { std::swap(block.second.width, block.second.height); std::swap(block.second.x, block.second.y); diff --git a/src/widgets/GraphHorizontalAdapter.h b/src/widgets/GraphHorizontalAdapter.h index 3f27b98d..4052c9cc 100644 --- a/src/widgets/GraphHorizontalAdapter.h +++ b/src/widgets/GraphHorizontalAdapter.h @@ -13,11 +13,10 @@ class GraphHorizontalAdapter : public GraphLayout { public: GraphHorizontalAdapter(std::unique_ptr layout); - virtual void CalculateLayout(GraphLayout::Graph &blocks, - ut64 entry, - int &width, + virtual void CalculateLayout(GraphLayout::Graph &blocks, ut64 entry, int &width, int &height) const override; void setLayoutConfig(const LayoutConfig &config) override; + private: std::unique_ptr layout; void swapLayoutConfigDirection(); diff --git a/src/widgets/GraphLayout.h b/src/widgets/GraphLayout.h index 6bc14132..4e1caa5c 100644 --- a/src/widgets/GraphLayout.h +++ b/src/widgets/GraphLayout.h @@ -8,18 +8,18 @@ class GraphLayout { public: - struct GraphEdge { + struct GraphEdge + { ut64 target; QPolygonF polyline; - enum ArrowDirection { - Down, Left, Up, Right, None - }; + enum ArrowDirection { Down, Left, Up, Right, None }; ArrowDirection arrow = ArrowDirection::Down; - explicit GraphEdge(ut64 target): target(target) {} + explicit GraphEdge(ut64 target) : target(target) {} }; - struct GraphBlock { + struct GraphBlock + { int x = 0; int y = 0; int width = 0; @@ -31,7 +31,8 @@ public: }; using Graph = std::unordered_map; - struct LayoutConfig { + struct LayoutConfig + { int blockVerticalSpacing = 40; int blockHorizontalSpacing = 20; int edgeVerticalSpacing = 10; @@ -40,12 +41,9 @@ public: GraphLayout(const LayoutConfig &layout_config) : layoutConfig(layout_config) {} virtual ~GraphLayout() {} - virtual void CalculateLayout(Graph &blocks, ut64 entry, int &width, - int &height) const = 0; - virtual void setLayoutConfig(const LayoutConfig &config) - { - this->layoutConfig = config; - }; + virtual void CalculateLayout(Graph &blocks, ut64 entry, int &width, int &height) const = 0; + virtual void setLayoutConfig(const LayoutConfig &config) { this->layoutConfig = config; }; + protected: LayoutConfig layoutConfig; }; diff --git a/src/widgets/GraphView.cpp b/src/widgets/GraphView.cpp index 83179360..4af3eabb 100644 --- a/src/widgets/GraphView.cpp +++ b/src/widgets/GraphView.cpp @@ -2,7 +2,7 @@ #include "GraphGridLayout.h" #ifdef CUTTER_ENABLE_GRAPHVIZ -#include "GraphvizLayout.h" +# include "GraphvizLayout.h" #endif #include "GraphHorizontalAdapter.h" #include "Helpers.h" @@ -15,18 +15,19 @@ #include #ifndef CUTTER_NO_OPENGL_GRAPH -#include -#include -#include -#include +# include +# include +# include +# include #endif GraphView::GraphView(QWidget *parent) - : QAbstractScrollArea(parent) - , useGL(false) + : QAbstractScrollArea(parent), + useGL(false) #ifndef CUTTER_NO_OPENGL_GRAPH - , cacheTexture(0) - , cacheFBO(0) + , + cacheTexture(0), + cacheFBO(0) #endif { #ifndef CUTTER_NO_OPENGL_GRAPH @@ -40,9 +41,7 @@ GraphView::GraphView(QWidget *parent) setGraphLayout(makeGraphLayout(Layout::GridMedium)); } -GraphView::~GraphView() -{ -} +GraphView::~GraphView() {} // Callbacks @@ -94,9 +93,7 @@ GraphView::EdgeConfiguration GraphView::edgeConfiguration(GraphView::GraphBlock return ec; } -void GraphView::blockContextMenuRequested(GraphView::GraphBlock &, QContextMenuEvent *, QPoint) -{ -} +void GraphView::blockContextMenuRequested(GraphView::GraphBlock &, QContextMenuEvent *, QPoint) {} bool GraphView::event(QEvent *event) { @@ -147,8 +144,8 @@ void GraphView::cleanupEdges(GraphLayout::Graph &graph) for (auto it = block.edges.begin(), end = block.edges.end(); it != end; ++it) { // remove edges going to different functions // and remove duplicate edges, common in switch statements - if (graph.find(it->target) != graph.end() && - seenEdges.find(it->target) == seenEdges.end()) { + if (graph.find(it->target) != graph.end() + && seenEdges.find(it->target) == seenEdges.end()) { *outIt++ = *it; seenEdges.insert(it->target); } @@ -181,18 +178,18 @@ QSize GraphView::getCacheSize() { return #ifndef CUTTER_NO_OPENGL_GRAPH - useGL ? cacheSize : + useGL ? cacheSize : #endif - pixmap.size(); + pixmap.size(); } qreal GraphView::getCacheDevicePixelRatioF() { return #ifndef CUTTER_NO_OPENGL_GRAPH - useGL ? 1.0 : + useGL ? 1.0 : #endif - qhelpers::devicePixelRatio(&pixmap); + qhelpers::devicePixelRatio(&pixmap); } QSize GraphView::getRequiredCacheSize() @@ -204,9 +201,9 @@ qreal GraphView::getRequiredCacheDevicePixelRatioF() { return #ifndef CUTTER_NO_OPENGL_GRAPH - useGL ? 1.0f : + useGL ? 1.0f : #endif - qhelpers::devicePixelRatio(this); + qhelpers::devicePixelRatio(this); } void GraphView::paintEvent(QPaintEvent *) @@ -218,7 +215,7 @@ void GraphView::paintEvent(QPaintEvent *) #endif if (!qFuzzyCompare(getCacheDevicePixelRatioF(), getRequiredCacheDevicePixelRatioF()) - || getCacheSize() != getRequiredCacheSize()) { + || getCacheSize() != getRequiredCacheSize()) { setCacheDirty(); } @@ -233,8 +230,8 @@ void GraphView::paintEvent(QPaintEvent *) gl->glBindFramebuffer(GL_READ_FRAMEBUFFER, cacheFBO); gl->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, glWidget->defaultFramebufferObject()); auto dpr = qhelpers::devicePixelRatio(this); - gl->glBlitFramebuffer(0, 0, cacheSize.width(), cacheSize.height(), - 0, 0, viewport()->width() * dpr, viewport()->height() * dpr, + gl->glBlitFramebuffer(0, 0, cacheSize.width(), cacheSize.height(), 0, 0, + viewport()->width() * dpr, viewport()->height() * dpr, GL_COLOR_BUFFER_BIT, GL_NEAREST); glWidget->doneCurrent(); #endif @@ -247,12 +244,12 @@ void GraphView::paintEvent(QPaintEvent *) void GraphView::clampViewOffset() { const qreal edgeFraction = 0.25; - qreal edgeX = edgeFraction * (viewport()->width() / current_scale); - qreal edgeY = edgeFraction * (viewport()->height() / current_scale); + qreal edgeX = edgeFraction * (viewport()->width() / current_scale); + qreal edgeY = edgeFraction * (viewport()->height() / current_scale); offset.rx() = std::max(std::min(qreal(offset.x()), width - edgeX), - - viewport()->width() / current_scale + edgeX); + -viewport()->width() / current_scale + edgeX); offset.ry() = std::max(std::min(qreal(offset.y()), height - edgeY), - - viewport()->height() / current_scale + edgeY); + -viewport()->height() / current_scale + edgeY); } void GraphView::setViewOffsetInternal(QPoint pos, bool emitSignal) @@ -295,16 +292,18 @@ void GraphView::paintGraphCache() } if (resizeTex) { cacheSize = sizeNeed; - gl->glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, cacheSize.width(), cacheSize.height(), 0, GL_RGBA, - GL_UNSIGNED_BYTE, nullptr); + gl->glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, cacheSize.width(), cacheSize.height(), 0, + GL_RGBA, GL_UNSIGNED_BYTE, nullptr); gl->glGenFramebuffers(1, &cacheFBO); gl->glBindFramebuffer(GL_FRAMEBUFFER, cacheFBO); - gl->glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, cacheTexture, 0); + gl->glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, + cacheTexture, 0); } else { gl->glBindFramebuffer(GL_FRAMEBUFFER, cacheFBO); } gl->glViewport(0, 0, viewport()->width(), viewport()->height()); - gl->glClearColor(backgroundColor.redF(), backgroundColor.greenF(), backgroundColor.blueF(), 1.0f); + gl->glClearColor(backgroundColor.redF(), backgroundColor.greenF(), backgroundColor.blueF(), + 1.0f); gl->glClear(GL_COLOR_BUFFER_BIT); paintDevice.reset(new QOpenGLPaintDevice(cacheSize)); @@ -333,7 +332,8 @@ void GraphView::paint(QPainter &p, QPoint offset, QRect viewport, qreal scale, b int render_height = viewport.height(); // window - rectangle in logical coordinates - QRect window = QRect(offset, QSize(qRound(render_width / scale), qRound(render_height / scale))); + QRect window = + QRect(offset, QSize(qRound(render_width / scale), qRound(render_height / scale))); p.setWindow(window); QRectF windowF(window.x(), window.y(), window.width(), window.height()); @@ -485,7 +485,8 @@ void GraphView::showRectangle(const QRect &block, bool anywhere) if (width * current_scale <= viewport()->width()) { centerX(false); } else { - if (!anywhere || block.x() < offset.x() || block.right() > offset.x() + renderSize.width()) { + if (!anywhere || block.x() < offset.x() + || block.right() > offset.x() + renderSize.width()) { offset.rx() = block.x() - ((renderSize.width() - block.width()) / 2); } } @@ -493,7 +494,7 @@ void GraphView::showRectangle(const QRect &block, bool anywhere) centerY(false); } else { if (!anywhere || block.y() < offset.y() - || block.bottom() > offset.y() + renderSize.height()) { + || block.bottom() > offset.y() + renderSize.height()) { offset.ry() = block.y(); // Leave some space at top if possible const qreal topPadding = 10 / current_scale; @@ -551,8 +552,8 @@ std::unique_ptr GraphView::makeGraphLayout(GraphView::Layout layout #ifdef CUTTER_ENABLE_GRAPHVIZ auto makeGraphvizLayout = [&](GraphvizLayout::LayoutType type) { - result.reset(new GraphvizLayout(type, - horizontal ? GraphvizLayout::Direction::LR : GraphvizLayout::Direction::TB)); + result.reset(new GraphvizLayout( + type, horizontal ? GraphvizLayout::Direction::LR : GraphvizLayout::Direction::TB)); needAdapter = false; }; #endif @@ -623,10 +624,10 @@ void GraphView::setEntry(ut64 e) bool GraphView::checkPointClicked(QPointF &point, int x, int y, bool above_y) { int half_target_size = 5; - if ((point.x() - half_target_size < x) && - (point.y() - (above_y ? (2 * half_target_size) : 0) < y) && - (x < point.x() + half_target_size) && - (y < point.y() + (above_y ? 0 : (3 * half_target_size)))) { + if ((point.x() - half_target_size < x) + && (point.y() - (above_y ? (2 * half_target_size) : 0) < y) + && (x < point.x() + half_target_size) + && (y < point.y() + (above_y ? 0 : (3 * half_target_size)))) { return true; } return false; @@ -678,7 +679,7 @@ void GraphView::mousePressEvent(QMouseEvent *event) // No block was clicked if (event->button() == Qt::LeftButton) { - //Left click outside any block, enter scrolling mode + // Left click outside any block, enter scrolling mode beginMouseDrag(event); return; } @@ -689,7 +690,8 @@ void GraphView::mousePressEvent(QMouseEvent *event) void GraphView::mouseMoveEvent(QMouseEvent *event) { if (scroll_mode) { - addViewOffset(QPoint(scroll_base_x - event->x(), scroll_base_y - event->y()) / current_scale); + addViewOffset(QPoint(scroll_base_x - event->x(), scroll_base_y - event->y()) + / current_scale); scroll_base_x = event->x(); scroll_base_y = event->y(); viewport()->update(); diff --git a/src/widgets/GraphView.h b/src/widgets/GraphView.h index 73bd098b..5041179e 100644 --- a/src/widgets/GraphView.h +++ b/src/widgets/GraphView.h @@ -20,7 +20,7 @@ #if defined(QT_NO_OPENGL) || QT_VERSION < QT_VERSION_CHECK(5, 6, 0) // QOpenGLExtraFunctions were introduced in 5.6 -#define CUTTER_NO_OPENGL_GRAPH +# define CUTTER_NO_OPENGL_GRAPH #endif #ifndef CUTTER_NO_OPENGL_GRAPH @@ -40,29 +40,31 @@ public: using GraphEdge = GraphLayout::GraphEdge; enum class Layout { - GridNarrow - , GridMedium - , GridWide - , GridAAA - , GridAAB - , GridABA - , GridABB - , GridBAA - , GridBAB - , GridBBA - , GridBBB + GridNarrow, + GridMedium, + GridWide, + GridAAA, + GridAAB, + GridABA, + GridABB, + GridBAA, + GridBAB, + GridBBA, + GridBBB #ifdef CUTTER_ENABLE_GRAPHVIZ - , GraphvizOrtho - , GraphvizPolyline - , GraphvizSfdp - , GraphvizNeato - , GraphvizTwoPi - , GraphvizCirco + , + GraphvizOrtho, + GraphvizPolyline, + GraphvizSfdp, + GraphvizNeato, + GraphvizTwoPi, + GraphvizCirco #endif }; static std::unique_ptr makeGraphLayout(Layout layout, bool horizontal = false); - struct EdgeConfiguration { + struct EdgeConfiguration + { QColor color = QColor(128, 128, 128); bool start_arrow = false; bool end_arrow = true; @@ -106,6 +108,7 @@ public: * @param graph */ static void cleanupEdges(GraphLayout::Graph &graph); + protected: std::unordered_map blocks; /// image background color @@ -114,7 +117,7 @@ protected: // Padding inside the block int block_padding = 16; - void setCacheDirty() { cacheDirty = true; } + void setCacheDirty() { cacheDirty = true; } void addBlock(GraphView::GraphBlock block); void setEntry(ut64 e); @@ -133,16 +136,17 @@ protected: virtual bool helpEvent(QHelpEvent *event); virtual void blockTransitionedTo(GraphView::GraphBlock *to); virtual void wheelEvent(QWheelEvent *event) override; - virtual EdgeConfiguration edgeConfiguration(GraphView::GraphBlock &from, GraphView::GraphBlock *to, - bool interactive = true); + virtual EdgeConfiguration edgeConfiguration(GraphView::GraphBlock &from, + GraphView::GraphBlock *to, bool interactive = true); virtual bool gestureEvent(QGestureEvent *event); /** - * @brief Called when user requested context menu for a block. Should open a block specific contextmenu. - * Typically triggered by right click. + * @brief Called when user requested context menu for a block. Should open a block specific + * contextmenu. Typically triggered by right click. * @param block - the block that was clicked on - * @param event - context menu event that triggered the callback, can be used to display context menu - * at correct position - * @param pos - mouse click position in logical coordinates of the drawing, set only if event reason is mouse + * @param event - context menu event that triggered the callback, can be used to display context + * menu at correct position + * @param pos - mouse click position in logical coordinates of the drawing, set only if event + * reason is mouse */ virtual void blockContextMenuRequested(GraphView::GraphBlock &block, QContextMenuEvent *event, QPoint pos); @@ -214,15 +218,16 @@ private: qreal getRequiredCacheDevicePixelRatioF(); void beginMouseDrag(QMouseEvent *event); + public: - QPoint getViewOffset() const { return offset; } + QPoint getViewOffset() const { return offset; } void setViewOffset(QPoint offset); - qreal getViewScale() const { return current_scale; } + qreal getViewScale() const { return current_scale; } void setViewScale(qreal scale); void center(); - void centerX() { centerX(true); } - void centerY() { centerY(true); } + void centerX() { centerX(true); } + void centerY() { centerY(true); } }; #endif // GRAPHVIEW_H diff --git a/src/widgets/GraphWidget.cpp b/src/widgets/GraphWidget.cpp index 4ec60ad6..046babe0 100644 --- a/src/widgets/GraphWidget.cpp +++ b/src/widgets/GraphWidget.cpp @@ -4,12 +4,9 @@ #include "WidgetShortcuts.h" #include -GraphWidget::GraphWidget(MainWindow *main) : - MemoryDockWidget(MemoryWidgetType::Graph, main) +GraphWidget::GraphWidget(MainWindow *main) : MemoryDockWidget(MemoryWidgetType::Graph, main) { - setObjectName(main - ? main->getUniqueObjectName(getWidgetType()) - : getWidgetType()); + setObjectName(main ? main->getUniqueObjectName(getWidgetType()) : getWidgetType()); setAllowedAreas(Qt::AllDockWidgetAreas); @@ -23,7 +20,7 @@ GraphWidget::GraphWidget(MainWindow *main) : header->setReadOnly(true); layout->addWidget(header); - graphView = new DisassemblerGraphView(layoutWidget, seekable, main, {&syncAction}); + graphView = new DisassemblerGraphView(layoutWidget, seekable, main, { &syncAction }); layout->addWidget(graphView); // Title needs to get set after graphView is defined @@ -31,15 +28,14 @@ GraphWidget::GraphWidget(MainWindow *main) : // getting the name of the class is implementation defined, and cannot be // used reliably across different compilers. - //QShortcut *toggle_shortcut = new QShortcut(widgetShortcuts[typeid(this).name()], main); + // QShortcut *toggle_shortcut = new QShortcut(widgetShortcuts[typeid(this).name()], main); QShortcut *toggle_shortcut = new QShortcut(widgetShortcuts["GraphWidget"], main); - connect(toggle_shortcut, &QShortcut::activated, this, [ = ]() { - toggleDockWidget(true); - }); + connect(toggle_shortcut, &QShortcut::activated, this, [=]() { toggleDockWidget(true); }); - connect(graphView, &DisassemblerGraphView::nameChanged, this, &MemoryDockWidget::updateWindowTitle); + connect(graphView, &DisassemblerGraphView::nameChanged, this, + &MemoryDockWidget::updateWindowTitle); - connect(this, &QDockWidget::visibilityChanged, this, [ = ](bool visibility) { + connect(this, &QDockWidget::visibilityChanged, this, [=](bool visibility) { main->toggleOverview(visibility, this); if (visibility) { graphView->onSeekChanged(Core()->getOffset()); @@ -50,13 +46,11 @@ GraphWidget::GraphWidget(MainWindow *main) : switchAction->setShortcut(Qt::Key_Space); switchAction->setShortcutContext(Qt::WidgetWithChildrenShortcut); addAction(switchAction); - connect(switchAction, &QAction::triggered, this, [this] { - mainWindow->showMemoryWidget(MemoryWidgetType::Disassembly); - }); + connect(switchAction, &QAction::triggered, this, + [this] { mainWindow->showMemoryWidget(MemoryWidgetType::Disassembly); }); - connect(graphView, &DisassemblerGraphView::graphMoved, this, [ = ]() { - main->toggleOverview(true, this); - }); + connect(graphView, &DisassemblerGraphView::graphMoved, this, + [=]() { main->toggleOverview(true, this); }); connect(seekable, &CutterSeekable::seekableSeekChanged, this, &GraphWidget::prepareHeader); connect(Core(), &CutterCore::functionRenamed, this, &GraphWidget::prepareHeader); graphView->installEventFilter(this); @@ -98,4 +92,3 @@ void GraphWidget::prepareHeader() header->show(); header->setText(afcf); } - diff --git a/src/widgets/GraphvizLayout.cpp b/src/widgets/GraphvizLayout.cpp index ea6bc24d..f2a53b3c 100644 --- a/src/widgets/GraphvizLayout.cpp +++ b/src/widgets/GraphvizLayout.cpp @@ -12,9 +12,7 @@ #include GraphvizLayout::GraphvizLayout(LayoutType lineType, Direction direction) - : GraphLayout({}) - , direction(direction) - , layoutType(lineType) + : GraphLayout({}), direction(direction), layoutType(lineType) { } @@ -48,7 +46,7 @@ static std::set> SelectLoopEdges(const GraphLayout::Graph std::stack> stack; auto dfsFragment = [&visited, &graph, &stack, &result](ut64 first) { visited[first] = 1; - stack.push({first, 0}); + stack.push({ first, 0 }); while (!stack.empty()) { auto v = stack.top().first; auto edge_index = stack.top().second; @@ -63,9 +61,9 @@ static std::set> SelectLoopEdges(const GraphLayout::Graph auto &targetState = visited[target]; if (targetState == 0) { targetState = 1; - stack.push({target, 0}); + stack.push({ target, 0 }); } else if (targetState == 1) { - result.insert({v, target}); + result.insert({ v, target }); } } else { stack.pop(); @@ -87,8 +85,8 @@ static std::set> SelectLoopEdges(const GraphLayout::Graph void GraphvizLayout::CalculateLayout(std::unordered_map &blocks, ut64 entry, int &width, int &height) const { - //https://gitlab.com/graphviz/graphviz/issues/1441 -#define STR(v) const_cast(v) + // https://gitlab.com/graphviz/graphviz/issues/1441 +#define STR(v) const_cast(v) width = height = 10; GVC_t *gvc = gvContext(); @@ -103,7 +101,8 @@ void GraphvizLayout::CalculateLayout(std::unordered_map &block strc.reserve(2 * blocks.size()); std::map, Agedge_t *> edges; - agsafeset(g, STR("splines"), layoutType == LayoutType::DotOrtho ? STR("ortho") : STR("polyline"), STR("")); + agsafeset(g, STR("splines"), + layoutType == LayoutType::DotOrtho ? STR("ortho") : STR("polyline"), STR("")); switch (direction) { case Direction::LR: agsafeset(g, STR("rankdir"), STR("LR"), STR("")); @@ -145,8 +144,8 @@ void GraphvizLayout::CalculateLayout(std::unordered_map &block continue; } auto e = agedge(g, u, v->second, nullptr, TRUE); - edges[{blockIt.first, edge.target}] = e; - if (loopEdges.find({blockIt.first, edge.target}) != loopEdges.end()) { + edges[{ blockIt.first, edge.target }] = e; + if (loopEdges.find({ blockIt.first, edge.target }) != loopEdges.end()) { agxset(e, constraintAttr, STR("0")); } } @@ -184,13 +183,13 @@ void GraphvizLayout::CalculateLayout(std::unordered_map &block auto w = ND_width(u) * dpi; auto h = ND_height(u) * dpi; - block.x = pos.x - w / 2.0; - block.y = pos.y - h / 2.0; + block.x = pos.x - w / 2.0; + block.y = pos.y - h / 2.0; width = std::max(width, block.x + block.width); height = std::max(height, block.y + block.height); for (auto &edge : block.edges) { - auto it = edges.find({blockIt.first, edge.target}); + auto it = edges.find({ blockIt.first, edge.target }); if (it != edges.end()) { auto e = it->second; if (auto spl = ED_spl(e)) { @@ -212,13 +211,15 @@ void GraphvizLayout::CalculateLayout(std::unordered_map &block if (edge.polyline.size() >= 2) { // make sure self loops go from bottom to top - if (edge.target == block.entry && edge.polyline.first().y() < edge.polyline.last().y()) { + if (edge.target == block.entry + && edge.polyline.first().y() < edge.polyline.last().y()) { std::reverse(edge.polyline.begin(), edge.polyline.end()); } auto it = std::prev(edge.polyline.end()); QPointF direction = *it; direction -= *(--it); - edge.arrow = getArrowDirection(direction, layoutType == LayoutType::DotPolyline); + edge.arrow = getArrowDirection(direction, + layoutType == LayoutType::DotPolyline); } else { edge.arrow = GraphEdge::Down; diff --git a/src/widgets/GraphvizLayout.h b/src/widgets/GraphvizLayout.h index bc6475e1..88c02627 100644 --- a/src/widgets/GraphvizLayout.h +++ b/src/widgets/GraphvizLayout.h @@ -15,15 +15,11 @@ public: TwoPi, Circo, }; - enum class Direction { - TB, - LR - }; + enum class Direction { TB, LR }; GraphvizLayout(LayoutType layoutType, Direction direction = Direction::TB); - virtual void CalculateLayout(std::unordered_map &blocks, - ut64 entry, - int &width, - int &height) const override; + virtual void CalculateLayout(std::unordered_map &blocks, ut64 entry, + int &width, int &height) const override; + private: Direction direction; LayoutType layoutType; diff --git a/src/widgets/HeadersWidget.cpp b/src/widgets/HeadersWidget.cpp index 0d410e80..d5740734 100644 --- a/src/widgets/HeadersWidget.cpp +++ b/src/widgets/HeadersWidget.cpp @@ -4,8 +4,7 @@ #include "common/Helpers.h" HeadersModel::HeadersModel(QList *headers, QObject *parent) - : AddressableItemModel(parent), - headers(headers) + : AddressableItemModel(parent), headers(headers) { } @@ -88,16 +87,17 @@ HeadersProxyModel::HeadersProxyModel(HeadersModel *sourceModel, QObject *parent) bool HeadersProxyModel::filterAcceptsRow(int row, const QModelIndex &parent) const { QModelIndex index = sourceModel()->index(row, 0, parent); - HeaderDescription item = index.data(HeadersModel::HeaderDescriptionRole).value(); + HeaderDescription item = + index.data(HeadersModel::HeaderDescriptionRole).value(); return item.name.contains(filterRegExp()); } bool HeadersProxyModel::lessThan(const QModelIndex &left, const QModelIndex &right) const { - HeaderDescription leftHeader = left.data( - HeadersModel::HeaderDescriptionRole).value(); - HeaderDescription rightHeader = right.data( - HeadersModel::HeaderDescriptionRole).value(); + HeaderDescription leftHeader = + left.data(HeadersModel::HeaderDescriptionRole).value(); + HeaderDescription rightHeader = + right.data(HeadersModel::HeaderDescriptionRole).value(); switch (left.column()) { case HeadersModel::OffsetColumn: @@ -115,8 +115,7 @@ bool HeadersProxyModel::lessThan(const QModelIndex &left, const QModelIndex &rig return leftHeader.vaddr < rightHeader.vaddr; } -HeadersWidget::HeadersWidget(MainWindow *main) : - ListDockWidget(main) +HeadersWidget::HeadersWidget(MainWindow *main) : ListDockWidget(main) { setWindowTitle(tr("Headers")); setObjectName("HeadersWidget"); @@ -131,9 +130,8 @@ HeadersWidget::HeadersWidget(MainWindow *main) : connect(Core(), &CutterCore::codeRebased, this, &HeadersWidget::refreshHeaders); connect(Core(), &CutterCore::refreshAll, this, &HeadersWidget::refreshHeaders); - connect(Core(), &CutterCore::commentsChanged, this, [this]() { - qhelpers::emitColumnChanged(headersModel, HeadersModel::CommentColumn); - }); + connect(Core(), &CutterCore::commentsChanged, this, + [this]() { qhelpers::emitColumnChanged(headersModel, HeadersModel::CommentColumn); }); } HeadersWidget::~HeadersWidget() {} diff --git a/src/widgets/HeadersWidget.h b/src/widgets/HeadersWidget.h index 5f44640e..f4ed1499 100644 --- a/src/widgets/HeadersWidget.h +++ b/src/widgets/HeadersWidget.h @@ -16,13 +16,11 @@ namespace Ui { class HeadersWidget; } - class MainWindow; class QTreeWidgetItem; class HeadersWidget; - -class HeadersModel: public AddressableItemModel +class HeadersModel : public AddressableItemModel { Q_OBJECT @@ -41,14 +39,13 @@ public: int columnCount(const QModelIndex &parent = QModelIndex()) const override; QVariant data(const QModelIndex &index, int role) const override; - QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; + QVariant headerData(int section, Qt::Orientation orientation, + int role = Qt::DisplayRole) const override; RVA address(const QModelIndex &index) const override; QString name(const QModelIndex &index) const override; }; - - class HeadersProxyModel : public AddressableFilterProxyModel { Q_OBJECT @@ -61,8 +58,6 @@ protected: bool lessThan(const QModelIndex &left, const QModelIndex &right) const override; }; - - class HeadersWidget : public ListDockWidget { Q_OBJECT @@ -80,5 +75,4 @@ private: QList headers; }; - #endif // HEADERSWIDGET_H diff --git a/src/widgets/HexWidget.cpp b/src/widgets/HexWidget.cpp index 5d07b0be..ad49f015 100644 --- a/src/widgets/HexWidget.cpp +++ b/src/widgets/HexWidget.cpp @@ -26,30 +26,31 @@ static constexpr uint64_t MAX_COPY_SIZE = 128 * 1024 * 1024; static constexpr int MAX_LINE_WIDTH_PRESET = 32; static constexpr int MAX_LINE_WIDTH_BYTES = 128 * 1024; -HexWidget::HexWidget(QWidget *parent) : - QScrollArea(parent), - cursorEnabled(true), - cursorOnAscii(false), - updatingSelection(false), - itemByteLen(1), - itemGroupSize(1), - rowSizeBytes(16), - columnMode(ColumnMode::PowerOf2), - itemFormat(ItemFormatHex), - itemBigEndian(false), - addrCharLen(AddrWidth64), - showHeader(true), - showAscii(true), - showExHex(true), - showExAddr(true) +HexWidget::HexWidget(QWidget *parent) + : QScrollArea(parent), + cursorEnabled(true), + cursorOnAscii(false), + updatingSelection(false), + itemByteLen(1), + itemGroupSize(1), + rowSizeBytes(16), + columnMode(ColumnMode::PowerOf2), + itemFormat(ItemFormatHex), + itemBigEndian(false), + addrCharLen(AddrWidth64), + showHeader(true), + showAscii(true), + showExHex(true), + showExAddr(true) { setMouseTracking(true); setFocusPolicy(Qt::FocusPolicy::StrongFocus); - connect(horizontalScrollBar(), &QScrollBar::valueChanged, this, [this]() { viewport()->update(); }); + connect(horizontalScrollBar(), &QScrollBar::valueChanged, this, + [this]() { viewport()->update(); }); connect(Config(), &Configuration::colorsUpdated, this, &HexWidget::updateColors); - connect(Config(), &Configuration::fontsUpdated, this, [this]() { setMonospaceFont( - Config()->getFont()); }); + connect(Config(), &Configuration::fontsUpdated, this, + [this]() { setMonospaceFont(Config()->getFont()); }); auto sizeActionGroup = new QActionGroup(this); for (int i = 1; i <= 8; i *= 2) { @@ -74,7 +75,8 @@ HexWidget::HexWidget(QWidget *parent) : QAction *action = new QAction(names.at(i), this); action->setCheckable(true); action->setActionGroup(formatActionGroup); - connect(action, &QAction::triggered, this, [=]() { setItemFormat(static_cast(i)); }); + connect(action, &QAction::triggered, this, + [=]() { setItemFormat(static_cast(i)); }); actionsItemFormat.append(action); } actionsItemFormat.at(0)->setChecked(true); @@ -93,7 +95,8 @@ HexWidget::HexWidget(QWidget *parent) : actionRowSizePowerOf2 = new QAction(tr("Power of 2"), this); actionRowSizePowerOf2->setCheckable(true); actionRowSizePowerOf2->setActionGroup(columnsActionGroup); - connect(actionRowSizePowerOf2, &QAction::triggered, this, [=]() { setColumnMode(ColumnMode::PowerOf2); }); + connect(actionRowSizePowerOf2, &QAction::triggered, this, + [=]() { setColumnMode(ColumnMode::PowerOf2); }); rowSizeMenu->addAction(actionRowSizePowerOf2); actionItemBigEndian = new QAction(tr("Big Endian"), this); @@ -118,51 +121,51 @@ HexWidget::HexWidget(QWidget *parent) : addAction(actionCopyAddress); actionSelectRange = new QAction(tr("Select range"), this); - connect(actionSelectRange, &QAction::triggered, this, [this]() { rangeDialog.open(cursor.address); }); + connect(actionSelectRange, &QAction::triggered, this, + [this]() { rangeDialog.open(cursor.address); }); addAction(actionSelectRange); connect(&rangeDialog, &QDialog::accepted, this, &HexWidget::onRangeDialogAccepted); actionsWriteString.reserve(5); - QAction* actionWriteString = new QAction(tr("Write string"), this); + QAction *actionWriteString = new QAction(tr("Write string"), this); connect(actionWriteString, &QAction::triggered, this, &HexWidget::w_writeString); actionsWriteString.append(actionWriteString); - QAction* actionWriteLenString = new QAction(tr("Write length and string"), this); + QAction *actionWriteLenString = new QAction(tr("Write length and string"), this); connect(actionWriteLenString, &QAction::triggered, this, &HexWidget::w_writePascalString); actionsWriteString.append(actionWriteLenString); - QAction* actionWriteWideString = new QAction(tr("Write wide string"), this); + QAction *actionWriteWideString = new QAction(tr("Write wide string"), this); connect(actionWriteWideString, &QAction::triggered, this, &HexWidget::w_writeWideString); actionsWriteString.append(actionWriteWideString); - QAction* actionWriteCString = new QAction(tr("Write zero terminated string"), this); + QAction *actionWriteCString = new QAction(tr("Write zero terminated string"), this); connect(actionWriteCString, &QAction::triggered, this, &HexWidget::w_writeCString); actionsWriteString.append(actionWriteCString); - QAction* actionWrite64 = new QAction(tr("Write De\\Encoded Base64 string"), this); + QAction *actionWrite64 = new QAction(tr("Write De\\Encoded Base64 string"), this); connect(actionWrite64, &QAction::triggered, this, &HexWidget::w_write64); actionsWriteString.append(actionWrite64); actionsWriteOther.reserve(4); - QAction* actionWriteZeros = new QAction(tr("Write zeros"), this); + QAction *actionWriteZeros = new QAction(tr("Write zeros"), this); connect(actionWriteZeros, &QAction::triggered, this, &HexWidget::w_writeZeros); actionsWriteOther.append(actionWriteZeros); - QAction* actionWriteRandom = new QAction(tr("Write random bytes"), this); + QAction *actionWriteRandom = new QAction(tr("Write random bytes"), this); connect(actionWriteRandom, &QAction::triggered, this, &HexWidget::w_writeRandom); actionsWriteOther.append(actionWriteRandom); - QAction* actionDuplicateFromOffset = new QAction(tr("Duplicate from offset"), this); + QAction *actionDuplicateFromOffset = new QAction(tr("Duplicate from offset"), this); connect(actionDuplicateFromOffset, &QAction::triggered, this, &HexWidget::w_duplFromOffset); actionsWriteOther.append(actionDuplicateFromOffset); - QAction* actionIncDec = new QAction(tr("Increment/Decrement"), this); + QAction *actionIncDec = new QAction(tr("Increment/Decrement"), this); connect(actionIncDec, &QAction::triggered, this, &HexWidget::w_increaseDecrease); actionsWriteOther.append(actionIncDec); - connect(this, &HexWidget::selectionChanged, this, [this](Selection selection) { - actionCopy->setEnabled(!selection.empty); - }); + connect(this, &HexWidget::selectionChanged, this, + [this](Selection selection) { actionCopy->setEnabled(!selection.empty); }); updateMetrics(); updateItemLength(); @@ -182,10 +185,7 @@ HexWidget::HexWidget(QWidget *parent) : updateColors(); } -HexWidget::~HexWidget() -{ - -} +HexWidget::~HexWidget() {} void HexWidget::setMonospaceFont(const QFont &font) { @@ -204,7 +204,7 @@ void HexWidget::setMonospaceFont(const QFont &font) void HexWidget::setItemSize(int nbytes) { - static const QVector values({1, 2, 4, 8}); + static const QVector values({ 1, 2, 4, 8 }); if (!values.contains(nbytes)) return; @@ -234,7 +234,6 @@ void HexWidget::setItemFormat(ItemFormat format) actionsItemSize.at(0)->setEnabled(sizeEnabled); actionsItemSize.at(1)->setEnabled(sizeEnabled); - updateItemLength(); fetchData(); updateCursorMeta(); @@ -256,17 +255,19 @@ void HexWidget::setItemGroupSize(int size) /** * @brief Checks if Item at the address changed compared to the last read data. * @param address Address of Item to be compared. - * @return True if Item is different, False if Item is equal or last read didn't contain the address. + * @return True if Item is different, False if Item is equal or last read didn't contain the + * address. * @see HexWidget#readItem * * Checks if current Item at the address changed compared to the last read data. * It is assumed that the current read data buffer contains the address. */ -bool HexWidget::isItemDifferentAt(uint64_t address) { +bool HexWidget::isItemDifferentAt(uint64_t address) +{ char oldItem[sizeof(uint64_t)] = {}; char newItem[sizeof(uint64_t)] = {}; - if (data->copy(newItem, address, static_cast(itemByteLen)) && - oldData->copy(oldItem, address, static_cast(itemByteLen))) { + if (data->copy(newItem, address, static_cast(itemByteLen)) + && oldData->copy(oldItem, address, static_cast(itemByteLen))) { return memcmp(oldItem, newItem, sizeof(oldItem)) != 0; } return false; @@ -368,7 +369,7 @@ void HexWidget::clearSelection() HexWidget::Selection HexWidget::getSelection() { - return Selection{selection.isEmpty(), selection.start(), selection.end()}; + return Selection { selection.isEmpty(), selection.start(), selection.end() }; } void HexWidget::seek(uint64_t address) @@ -560,7 +561,8 @@ void HexWidget::wheelEvent(QWheelEvent *event) void HexWidget::keyPressEvent(QKeyEvent *event) { bool select = false; - auto moveOrSelect = [event, &select](QKeySequence::StandardKey moveSeq, QKeySequence::StandardKey selectSeq) ->bool { + auto moveOrSelect = [event, &select](QKeySequence::StandardKey moveSeq, + QKeySequence::StandardKey selectSeq) -> bool { if (event->matches(moveSeq)) { select = false; return true; @@ -589,7 +591,7 @@ void HexWidget::keyPressEvent(QKeyEvent *event) int linePos = int((cursor.address % itemRowByteLen()) - (startAddress % itemRowByteLen())); moveCursor(itemRowByteLen() - linePos, select); } - //viewport()->update(); + // viewport()->update(); } void HexWidget::contextMenuEvent(QContextMenuEvent *event) @@ -663,13 +665,13 @@ void HexWidget::copy() QClipboard *clipboard = QApplication::clipboard(); if (cursorOnAscii) { - clipboard->setText(Core()->cmdRawAt(QString("psx %1") - .arg(selection.size()), - selection.start()).trimmed()); + clipboard->setText( + Core()->cmdRawAt(QString("psx %1").arg(selection.size()), selection.start()) + .trimmed()); } else { - clipboard->setText(Core()->cmdRawAt(QString("p8 %1") - .arg(selection.size()), - selection.start()).trimmed()); //TODO: copy in the format shown + clipboard->setText(Core()->cmdRawAt(QString("p8 %1").arg(selection.size()), + selection.start()) + .trimmed()); // TODO: copy in the format shown } } @@ -700,12 +702,9 @@ void HexWidget::w_writeString() bool ok = false; QInputDialog d; d.setInputMode(QInputDialog::InputMode::TextInput); - QString str = d.getText(this, tr("Write string"), - tr("String:"), QLineEdit::Normal, "", &ok); + QString str = d.getText(this, tr("Write string"), tr("String:"), QLineEdit::Normal, "", &ok); if (ok && !str.isEmpty()) { - Core()->cmdRawAt(QString("w %1") - .arg(str), - getLocationAddress()); + Core()->cmdRawAt(QString("w %1").arg(str), getLocationAddress()); refresh(); } } @@ -722,10 +721,10 @@ void HexWidget::w_increaseDecrease() } QString mode = d.getMode() == IncrementDecrementDialog::Increase ? "+" : "-"; Core()->cmdRawAt(QString("w%1%2 %3") - .arg(QString::number(d.getNBytes())) - .arg(mode) - .arg(QString::number(d.getValue())), - getLocationAddress()); + .arg(QString::number(d.getNBytes())) + .arg(mode) + .arg(QString::number(d.getValue())), + getLocationAddress()); refresh(); } @@ -742,12 +741,10 @@ void HexWidget::w_writeZeros() size = static_cast(selection.size()); } - QString str = QString::number(d.getInt(this, tr("Write zeros"), - tr("Number of zeros:"), size, 1, 0x7FFFFFFF, 1, &ok)); + QString str = QString::number( + d.getInt(this, tr("Write zeros"), tr("Number of zeros:"), size, 1, 0x7FFFFFFF, 1, &ok)); if (ok && !str.isEmpty()) { - Core()->cmdRawAt(QString("w0 %1") - .arg(str), - getLocationAddress()); + Core()->cmdRawAt(QString("w0 %1").arg(str), getLocationAddress()); refresh(); } } @@ -765,18 +762,19 @@ void HexWidget::w_write64() QString mode = d.getMode() == Base64EnDecodedWriteDialog::Encode ? "e" : "d"; QByteArray str = d.getData(); - if (mode == "d" && (QString(str).contains(QRegularExpression("[^a-zA-Z0-9+/=]")) || - str.length() % 4 != 0 || str.isEmpty())) { - QMessageBox::critical(this, tr("Error"), - tr("Error occured during decoding your input.\n" - "Please, make sure, that it is a valid base64 string and try again.")); + if (mode == "d" + && (QString(str).contains(QRegularExpression("[^a-zA-Z0-9+/=]")) || str.length() % 4 != 0 + || str.isEmpty())) { + QMessageBox::critical( + this, tr("Error"), + tr("Error occured during decoding your input.\n" + "Please, make sure, that it is a valid base64 string and try again.")); return; } - Core()->cmdRawAt(QString("w6%1 %2") - .arg(mode) - .arg((mode == "e" ? str.toHex() : str).toStdString().c_str()), - getLocationAddress()); + Core()->cmdRawAt(QString("w6%1 %2").arg(mode).arg( + (mode == "e" ? str.toHex() : str).toStdString().c_str()), + getLocationAddress()); refresh(); } @@ -792,12 +790,10 @@ void HexWidget::w_writeRandom() if (!selection.isEmpty() && selection.size() <= INT_MAX) { size = static_cast(selection.size()); } - QString nbytes = QString::number(d.getInt(this, tr("Write random"), - tr("Number of bytes:"), size, 1, 0x7FFFFFFF, 1, &ok)); + QString nbytes = QString::number(d.getInt(this, tr("Write random"), tr("Number of bytes:"), + size, 1, 0x7FFFFFFF, 1, &ok)); if (ok && !nbytes.isEmpty()) { - Core()->cmdRawAt(QString("wr %1") - .arg(nbytes), - getLocationAddress()); + Core()->cmdRawAt(QString("wr %1").arg(nbytes), getLocationAddress()); refresh(); } } @@ -814,10 +810,7 @@ void HexWidget::w_duplFromOffset() } RVA copyFrom = d.getOffset(); QString nBytes = QString::number(d.getNBytes()); - Core()->cmdRawAt(QString("wd %1 %2") - .arg(copyFrom) - .arg(nBytes), - getLocationAddress()); + Core()->cmdRawAt(QString("wd %1 %2").arg(copyFrom).arg(nBytes), getLocationAddress()); refresh(); } @@ -829,12 +822,10 @@ void HexWidget::w_writePascalString() bool ok = false; QInputDialog d; d.setInputMode(QInputDialog::InputMode::TextInput); - QString str = d.getText(this, tr("Write Pascal string"), - tr("String:"), QLineEdit::Normal, "", &ok); + QString str = + d.getText(this, tr("Write Pascal string"), tr("String:"), QLineEdit::Normal, "", &ok); if (ok && !str.isEmpty()) { - Core()->cmdRawAt(QString("ws %1") - .arg(str), - getLocationAddress()); + Core()->cmdRawAt(QString("ws %1").arg(str), getLocationAddress()); refresh(); } } @@ -847,12 +838,10 @@ void HexWidget::w_writeWideString() bool ok = false; QInputDialog d; d.setInputMode(QInputDialog::InputMode::TextInput); - QString str = d.getText(this, tr("Write wide string"), - tr("String:"), QLineEdit::Normal, "", &ok); + QString str = + d.getText(this, tr("Write wide string"), tr("String:"), QLineEdit::Normal, "", &ok); if (ok && !str.isEmpty()) { - Core()->cmdRawAt(QString("ww %1") - .arg(str), - getLocationAddress()); + Core()->cmdRawAt(QString("ww %1").arg(str), getLocationAddress()); refresh(); } } @@ -865,12 +854,10 @@ void HexWidget::w_writeCString() bool ok = false; QInputDialog d; d.setInputMode(QInputDialog::InputMode::TextInput); - QString str = d.getText(this, tr("Write zero-terminated string"), - tr("String:"), QLineEdit::Normal, "", &ok); + QString str = d.getText(this, tr("Write zero-terminated string"), tr("String:"), + QLineEdit::Normal, "", &ok); if (ok && !str.isEmpty()) { - Core()->cmdRawAt(QString("wz %1") - .arg(str), - getLocationAddress()); + Core()->cmdRawAt(QString("wz %1").arg(str), getLocationAddress()); refresh(); } } @@ -945,7 +932,8 @@ void HexWidget::drawHeader(QPainter &painter) for (int j = 0; j < itemColumns; ++j) { for (int k = 0; k < itemGroupSize; ++k, offset += itemByteLen) { - painter.drawText(rect, Qt::AlignVCenter | Qt::AlignRight, QString::number(offset, 16).toUpper()); + painter.drawText(rect, Qt::AlignVCenter | Qt::AlignRight, + QString::number(offset, 16).toUpper()); rect.translate(itemWidth(), 0); } rect.translate(columnSpacingWidth(), 0); @@ -954,7 +942,8 @@ void HexWidget::drawHeader(QPainter &painter) rect.moveLeft(asciiArea.left()); rect.setWidth(charWidth); for (int j = 0; j < itemRowByteLen(); ++j) { - painter.drawText(rect, Qt::AlignVCenter | Qt::AlignRight, QString::number(j % 16, 16).toUpper()); + painter.drawText(rect, Qt::AlignVCenter | Qt::AlignRight, + QString::number(j % 16, 16).toUpper()); rect.translate(charWidth, 0); } } @@ -989,9 +978,8 @@ void HexWidget::drawAddrArea(QPainter &painter) QRectF strRect(addrArea.topLeft(), areaSize); painter.setPen(addrColor); - for (int line = 0; - line < visibleLines && offset <= data->maxIndex(); - ++line, strRect.translate(0, lineHeight), offset += itemRowByteLen()) { + for (int line = 0; line < visibleLines && offset <= data->maxIndex(); + ++line, strRect.translate(0, lineHeight), offset += itemRowByteLen()) { addrString = QString("%1").arg(offset, addrCharLen, 16, QLatin1Char('0')); if (showExAddr) addrString.prepend(hexPrefix); @@ -1016,7 +1004,8 @@ void HexWidget::drawItemArea(QPainter &painter) for (int line = 0; line < visibleLines; ++line) { itemRect.moveLeft(itemArea.left()); for (int j = 0; j < itemColumns; ++j) { - for (int k = 0; k < itemGroupSize && itemAddr <= data->maxIndex(); ++k, itemAddr += itemByteLen) { + for (int k = 0; k < itemGroupSize && itemAddr <= data->maxIndex(); + ++k, itemAddr += itemByteLen) { itemString = renderItem(itemAddr - startAddress, &itemColor); if (!getFlagsAndComment(itemAddr).isEmpty()) { @@ -1026,7 +1015,7 @@ void HexWidget::drawItemArea(QPainter &painter) painter.setPen(markerColor); painter.drawPolyline(shape); } - if (selection.contains(itemAddr) && !cursorOnAscii) { + if (selection.contains(itemAddr) && !cursorOnAscii) { itemColor = palette().highlightedText().color(); } if (isItemDifferentAt(itemAddr)) { @@ -1077,7 +1066,7 @@ void HexWidget::drawAsciiArea(QPainter &painter) qreal a = cursor.screenPos.width(); QPointF p = charRect.bottomLeft(); p.rx() += (charWidth - a) / 2 + 1; - p.ry() += - 2 * a; + p.ry() += -2 * a; painter.fillRect(QRectF(p, QSizeF(a, a)), color); } else { painter.drawText(charRect, Qt::AlignVCenter, ascii); @@ -1342,7 +1331,7 @@ const QColor HexWidget::itemColor(uint8_t byte) } template -static T fromBigEndian(const void * src) +static T fromBigEndian(const void *src) { #if QT_VERSION >= QT_VERSION_CHECK(5, 12, 0) return qFromBigEndian(src); @@ -1354,7 +1343,7 @@ static T fromBigEndian(const void * src) } template -static T fromLittleEndian(const void * src) +static T fromLittleEndian(const void *src) { #if QT_VERSION >= QT_VERSION_CHECK(5, 12, 0) return qFromLittleEndian(src); @@ -1419,10 +1408,10 @@ QVariant HexWidget::readItem(int offset, QColor *color) qword = fromLittleEndian(bytes); if (itemFormat == ItemFormatFloat) { memcpy(&float64, &qword, sizeof(float64)); - return QVariant(float64); + return QVariant(float64); } if (!signedItem) - return QVariant(qword); + return QVariant(qword); return QVariant(static_cast(qword)); } @@ -1435,7 +1424,7 @@ QString HexWidget::renderItem(int offset, QColor *color) QVariant itemVal = readItem(offset, color); int itemLen = itemCharLen - itemPrefixLen; /* Reserve space for prefix */ - //FIXME: handle broken itemVal ( QVariant() ) + // FIXME: handle broken itemVal ( QVariant() ) switch (itemFormat) { case ItemFormatHex: item = QString("%1").arg(itemVal.toULongLong(), itemLen, 16, QLatin1Char('0')); @@ -1499,7 +1488,7 @@ void HexWidget::fetchData() data->fetch(startAddress, bytesPerScreen()); } -BasicCursor HexWidget::screenPosToAddr(const QPoint &point, bool middle) const +BasicCursor HexWidget::screenPosToAddr(const QPoint &point, bool middle) const { QPointF pt = point - itemArea.topLeft(); @@ -1536,7 +1525,8 @@ BasicCursor HexWidget::currentAreaPosToAddr(const QPoint &point, bool middle) co BasicCursor HexWidget::mousePosToAddr(const QPoint &point, bool middle) const { - return asciiArea.contains(point) ? asciiPosToAddr(point, middle) : screenPosToAddr(point, middle); + return asciiArea.contains(point) ? asciiPosToAddr(point, middle) + : screenPosToAddr(point, middle); } QRectF HexWidget::itemRectangle(int offset) @@ -1579,6 +1569,7 @@ QRectF HexWidget::asciiRectangle(int offset) return QRectF(p, QSizeF(charWidth, lineHeight)); } -RVA HexWidget::getLocationAddress() { +RVA HexWidget::getLocationAddress() +{ return !selection.isEmpty() ? selection.start() : cursor.address; } diff --git a/src/widgets/HexWidget.h b/src/widgets/HexWidget.h index 5b2aa47c..1489ef85 100644 --- a/src/widgets/HexWidget.h +++ b/src/widgets/HexWidget.h @@ -46,15 +46,16 @@ struct BasicCursor } return *this; } - bool operator<(const BasicCursor &r) - { - return address < r.address || (pastEnd < r.pastEnd); - } + bool operator<(const BasicCursor &r) { return address < r.address || (pastEnd < r.pastEnd); } }; struct HexCursor { - HexCursor() { isVisible = false; onAsciiArea = false; } + HexCursor() + { + isVisible = false; + onAsciiArea = false; + } bool isVisible; bool onAsciiArea; @@ -83,10 +84,7 @@ public: class BufferData : public AbstractData { public: - BufferData() - { - m_buffer.fill(0, 1); - } + BufferData() { m_buffer.fill(0, 1); } BufferData(const QByteArray &buffer) { @@ -99,20 +97,19 @@ public: ~BufferData() override {} - void fetch(uint64_t, int) override { } + void fetch(uint64_t, int) override {} - bool copy(void *out, uint64_t addr, size_t len) override { - if (addr < static_cast(m_buffer.size()) && (static_cast(m_buffer.size()) - addr) < len) { + bool copy(void *out, uint64_t addr, size_t len) override + { + if (addr < static_cast(m_buffer.size()) + && (static_cast(m_buffer.size()) - addr) < len) { memcpy(out, m_buffer.constData() + addr, len); return true; } return false; } - uint64_t maxIndex() override - { - return m_buffer.size() - 1; - } + uint64_t maxIndex() override { return m_buffer.size() - 1; } private: QByteArray m_buffer; @@ -145,9 +142,12 @@ public: } } - bool copy(void *out, uint64_t addr, size_t len) override { - if (addr < m_firstBlockAddr || addr > m_lastValidAddr || - (m_lastValidAddr - addr + 1) < len /* do not merge with last check to handle overflows */ || m_blocks.isEmpty()) { + bool copy(void *out, uint64_t addr, size_t len) override + { + if (addr < m_firstBlockAddr || addr > m_lastValidAddr + || (m_lastValidAddr - addr + 1) + < len /* do not merge with last check to handle overflows */ + || m_blocks.isEmpty()) { return false; } @@ -159,20 +159,15 @@ public: memcpy(out, m_blocks.at(blockId).constData() + blockOffset, len); } else { memcpy(out, m_blocks.at(blockId).constData() + blockOffset, first_part); - memcpy(static_cast(out) + first_part, m_blocks.at(blockId + 1).constData(), len - first_part); + memcpy(static_cast(out) + first_part, m_blocks.at(blockId + 1).constData(), + len - first_part); } return true; } - virtual uint64_t maxIndex() override - { - return m_lastValidAddr; - } + virtual uint64_t maxIndex() override { return m_lastValidAddr; } - virtual uint64_t minIndex() override - { - return m_firstBlockAddr; - } + virtual uint64_t minIndex() override { return m_firstBlockAddr; } private: QVector m_blocks; @@ -222,10 +217,7 @@ public: return !m_empty && m_end >= start && m_start <= end; } - bool contains(uint64_t pos) const - { - return !m_empty && m_start <= pos && pos <= m_end; - } + bool contains(uint64_t pos) const { return !m_empty && m_start <= pos && pos <= m_end; } uint64_t size() { @@ -258,7 +250,13 @@ public: enum AddrWidth { AddrWidth32 = 8, AddrWidth64 = 16 }; enum ItemSize { ItemSizeByte = 1, ItemSizeWord = 2, ItemSizeDword = 4, ItemSizeQword = 8 }; - enum ItemFormat { ItemFormatHex, ItemFormatOct, ItemFormatDec, ItemFormatSignedDec, ItemFormatFloat }; + enum ItemFormat { + ItemFormatHex, + ItemFormatOct, + ItemFormatDec, + ItemFormatSignedDec, + ItemFormatFloat + }; enum class ColumnMode { Fixed, PowerOf2 }; void setItemSize(int nbytes); @@ -267,7 +265,8 @@ public: void setItemGroupSize(int size); /** * @brief Sets line size in bytes. - * Changes column mode to fixed. Command can be rejected if current item format is bigger than requested size. + * Changes column mode to fixed. Command can be rejected if current item format is bigger than + * requested size. * @param bytes line size in bytes. */ void setFixedLineSize(int bytes); @@ -281,7 +280,8 @@ public: void selectRange(RVA start, RVA end); void clearSelection(); - struct Selection { + struct Selection + { bool empty; RVA startAddress; RVA endAddress; @@ -347,7 +347,8 @@ private: QString getFlagsAndComment(uint64_t address); /** * @brief Get the location on which operations such as Writing should apply. - * @return Start of selection if multiple bytes are selected. Otherwise, the curren seek of the widget. + * @return Start of selection if multiple bytes are selected. Otherwise, the curren seek of the + * widget. */ RVA getLocationAddress(); @@ -355,8 +356,9 @@ private: /** * @brief Convert mouse position to address. * @param point mouse position in widget - * @param middle start next position from middle of symbol. Use middle=true for vertical cursror position between symbols, - * middle=false for insert mode cursor and getting symbol under cursor. + * @param middle start next position from middle of symbol. Use middle=true for vertical cursror + * position between symbols, middle=false for insert mode cursor and getting symbol under + * cursor. * @return */ BasicCursor screenPosToAddr(const QPoint &point, bool middle = false) const; @@ -378,80 +380,35 @@ private: QVector rangePolygons(RVA start, RVA last, bool ascii); void updateWidth(); - inline qreal itemWidth() const - { - return itemCharLen * charWidth; - } + inline qreal itemWidth() const { return itemCharLen * charWidth; } - inline int itemGroupCharLen() const - { - return itemCharLen * itemGroupSize; - } + inline int itemGroupCharLen() const { return itemCharLen * itemGroupSize; } - inline int columnExCharLen() const - { - return itemGroupCharLen() + columnSpacing; - } + inline int columnExCharLen() const { return itemGroupCharLen() + columnSpacing; } - inline int itemGroupByteLen() const - { - return itemByteLen * itemGroupSize; - } + inline int itemGroupByteLen() const { return itemByteLen * itemGroupSize; } - inline qreal columnWidth() const - { - return itemGroupCharLen() * charWidth; - } + inline qreal columnWidth() const { return itemGroupCharLen() * charWidth; } - inline qreal columnExWidth() const - { - return columnExCharLen() * charWidth; - } + inline qreal columnExWidth() const { return columnExCharLen() * charWidth; } - inline qreal columnSpacingWidth() const - { - return columnSpacing * charWidth; - } + inline qreal columnSpacingWidth() const { return columnSpacing * charWidth; } - inline int itemRowCharLen() const - { - return itemColumns * columnExCharLen() - columnSpacing; - } + inline int itemRowCharLen() const { return itemColumns * columnExCharLen() - columnSpacing; } - inline int itemRowByteLen() const - { - return rowSizeBytes; - } + inline int itemRowByteLen() const { return rowSizeBytes; } - inline int bytesPerScreen() const - { - return itemRowByteLen() * visibleLines; - } + inline int bytesPerScreen() const { return itemRowByteLen() * visibleLines; } - inline qreal itemRowWidth() const - { - return itemRowCharLen() * charWidth; - } + inline qreal itemRowWidth() const { return itemRowCharLen() * charWidth; } - inline qreal asciiRowWidth() const - { - return itemRowByteLen() * charWidth; - } + inline qreal asciiRowWidth() const { return itemRowByteLen() * charWidth; } - inline qreal areaSpacingWidth() const - { - return areaSpacing * charWidth; - } + inline qreal areaSpacingWidth() const { return areaSpacing * charWidth; } - inline uint64_t lastVisibleAddr() const - { - return (startAddress - 1) + bytesPerScreen(); - } + inline uint64_t lastVisibleAddr() const { return (startAddress - 1) + bytesPerScreen(); } - const QRectF ¤tArea() const - { - return cursorOnAscii ? asciiArea : itemArea; - } + const QRectF ¤tArea() const { return cursorOnAscii ? asciiArea : itemArea; } bool cursorEnabled; bool cursorOnAscii; @@ -501,7 +458,7 @@ private: QColor b0xffColor; QColor printableColor; - HexdumpRangeDialog rangeDialog; + HexdumpRangeDialog rangeDialog; /* Spacings in characters */ const int columnSpacing = 1; @@ -509,8 +466,8 @@ private: const QString hexPrefix = QStringLiteral("0x"); - QMenu* rowSizeMenu; - QAction* actionRowSizePowerOf2; + QMenu *rowSizeMenu; + QAction *actionRowSizePowerOf2; QList actionsItemSize; QList actionsItemFormat; QAction *actionItemBigEndian; @@ -524,7 +481,6 @@ private: std::unique_ptr oldData; std::unique_ptr data; IOModesController ioModesController; - }; #endif // HEXWIDGET_H diff --git a/src/widgets/HexdumpWidget.cpp b/src/widgets/HexdumpWidget.cpp index 7ce79f4b..e636b2aa 100644 --- a/src/widgets/HexdumpWidget.cpp +++ b/src/widgets/HexdumpWidget.cpp @@ -17,15 +17,12 @@ #include #include -HexdumpWidget::HexdumpWidget(MainWindow *main) : - MemoryDockWidget(MemoryWidgetType::Hexdump, main), - ui(new Ui::HexdumpWidget) +HexdumpWidget::HexdumpWidget(MainWindow *main) + : MemoryDockWidget(MemoryWidgetType::Hexdump, main), ui(new Ui::HexdumpWidget) { ui->setupUi(this); - setObjectName(main - ? main->getUniqueObjectName(getWidgetType()) - : getWidgetType()); + setObjectName(main ? main->getUniqueObjectName(getWidgetType()) : getWidgetType()); updateWindowTitle(); ui->copyMD5->setIcon(QIcon(":/img/icons/copy.svg")); @@ -33,7 +30,6 @@ HexdumpWidget::HexdumpWidget(MainWindow *main) : ui->copySHA256->setIcon(QIcon(":/img/icons/copy.svg")); ui->copyCRC32->setIcon(QIcon(":/img/icons/copy.svg")); - ui->splitter->setChildrenCollapsible(false); QToolButton *closeButton = new QToolButton; @@ -44,15 +40,11 @@ HexdumpWidget::HexdumpWidget(MainWindow *main) : ui->hexSideTab_2->setCornerWidget(closeButton); syntaxHighLighter = Config()->createSyntaxHighlighter(ui->hexDisasTextEdit->document()); - ui->openSideViewB->hide(); // hide button at startup since side view is visible + ui->openSideViewB->hide(); // hide button at startup since side view is visible - connect(closeButton, &QToolButton::clicked, this, [this] { - showSidePanel(false); - }); + connect(closeButton, &QToolButton::clicked, this, [this] { showSidePanel(false); }); - connect(ui->openSideViewB, &QToolButton::clicked, this, [this] { - showSidePanel(true); - }); + connect(ui->openSideViewB, &QToolButton::clicked, this, [this] { showSidePanel(true); }); // Set placeholders for the line-edit components QString placeholder = tr("Select bytes to display information"); @@ -77,9 +69,8 @@ HexdumpWidget::HexdumpWidget(MainWindow *main) : " border-color : #3daee9" "}"); - refreshDeferrer = createReplacingRefreshDeferrer(false, [this](const RVA *offset) { - refresh(offset ? *offset : RVA_INVALID); - }); + refreshDeferrer = createReplacingRefreshDeferrer( + false, [this](const RVA *offset) { refresh(offset ? *offset : RVA_INVALID); }); this->ui->hexTextView->addAction(&syncAction); @@ -99,7 +90,8 @@ HexdumpWidget::HexdumpWidget(MainWindow *main) : } }); connect(ui->hexTextView, &HexWidget::selectionChanged, this, &HexdumpWidget::selectionChanged); - connect(ui->hexSideTab_2, &QTabWidget::currentChanged, this, &HexdumpWidget::refreshSelectionInfo); + connect(ui->hexSideTab_2, &QTabWidget::currentChanged, this, + &HexdumpWidget::refreshSelectionInfo); ui->hexTextView->installEventFilter(this); initParsing(); @@ -145,7 +137,6 @@ void HexdumpWidget::refresh(RVA addr) sent_seek = false; } - void HexdumpWidget::initParsing() { // Fill the plugins combo for the hexdump sidebar @@ -172,16 +163,17 @@ void HexdumpWidget::selectionChanged(HexWidget::Selection selection) if (selection.empty) { clearParseWindow(); } else { - updateParseWindow(selection.startAddress, selection.endAddress - selection.startAddress + 1); + updateParseWindow(selection.startAddress, + selection.endAddress - selection.startAddress + 1); } } -void HexdumpWidget::on_parseArchComboBox_currentTextChanged(const QString &/*arg1*/) +void HexdumpWidget::on_parseArchComboBox_currentTextChanged(const QString & /*arg1*/) { refreshSelectionInfo(); } -void HexdumpWidget::on_parseBitsComboBox_currentTextChanged(const QString &/*arg1*/) +void HexdumpWidget::on_parseBitsComboBox_currentTextChanged(const QString & /*arg1*/) { refreshSelectionInfo(); } @@ -244,22 +236,24 @@ void HexdumpWidget::updateParseWindow(RVA start_address, int size) bool bigEndian = ui->parseEndianComboBox->currentIndex() == 1; TempConfig tempConfig; - tempConfig - .set("asm.arch", arch) - .set("asm.bits", bits) - .set("cfg.bigendian", bigEndian); + tempConfig.set("asm.arch", arch).set("asm.bits", bits).set("cfg.bigendian", bigEndian); - ui->hexDisasTextEdit->setPlainText(selectedCommand != "" ? Core()->cmdRawAt(QString("%1 %2") - .arg(selectedCommand) - .arg(size) - , start_address) : ""); + ui->hexDisasTextEdit->setPlainText( + selectedCommand != "" ? Core()->cmdRawAt( + QString("%1 %2").arg(selectedCommand).arg(size), start_address) + : ""); } else { // Fill the information tab hashes and entropy - ui->bytesMD5->setText(Core()->cmdRawAt(QString("ph md5 %1").arg(size), start_address).trimmed()); - ui->bytesSHA1->setText(Core()->cmdRawAt(QString("ph sha1 %1").arg(size), start_address).trimmed()); - ui->bytesSHA256->setText(Core()->cmdRawAt(QString("ph sha256 %1").arg(size), start_address).trimmed()); - ui->bytesCRC32->setText(Core()->cmdRawAt(QString("ph crc32 %1").arg(size), start_address).trimmed()); - ui->bytesEntropy->setText(Core()->cmdRawAt(QString("ph entropy %1").arg(size), start_address).trimmed()); + ui->bytesMD5->setText( + Core()->cmdRawAt(QString("ph md5 %1").arg(size), start_address).trimmed()); + ui->bytesSHA1->setText( + Core()->cmdRawAt(QString("ph sha1 %1").arg(size), start_address).trimmed()); + ui->bytesSHA256->setText( + Core()->cmdRawAt(QString("ph sha256 %1").arg(size), start_address).trimmed()); + ui->bytesCRC32->setText( + Core()->cmdRawAt(QString("ph crc32 %1").arg(size), start_address).trimmed()); + ui->bytesEntropy->setText( + Core()->cmdRawAt(QString("ph entropy %1").arg(size), start_address).trimmed()); ui->bytesMD5->setCursorPosition(0); ui->bytesSHA1->setCursorPosition(0); ui->bytesSHA256->setCursorPosition(0); @@ -302,7 +296,6 @@ void HexdumpWidget::on_hexSideTab_2_currentChanged(int /*index*/) */ } - void HexdumpWidget::resizeEvent(QResizeEvent *event) { // Heuristics to hide sidebar when it hides the content of the hexdump. 600px looks just "okay" diff --git a/src/widgets/HexdumpWidget.h b/src/widgets/HexdumpWidget.h index 6980977c..aa80fdf0 100644 --- a/src/widgets/HexdumpWidget.h +++ b/src/widgets/HexdumpWidget.h @@ -41,6 +41,7 @@ public slots: protected: virtual void resizeEvent(QResizeEvent *event) override; QWidget *widgetToFocusOnRaise() override; + private: std::unique_ptr ui; diff --git a/src/widgets/ImportsWidget.cpp b/src/widgets/ImportsWidget.cpp index 9f20e1b1..50b99ddb 100644 --- a/src/widgets/ImportsWidget.cpp +++ b/src/widgets/ImportsWidget.cpp @@ -9,10 +9,10 @@ #include #include -ImportsModel::ImportsModel(QList *imports, QObject *parent) : - AddressableItemModel(parent), - imports(imports) -{} +ImportsModel::ImportsModel(QList *imports, QObject *parent) + : AddressableItemModel(parent), imports(imports) +{ +} int ImportsModel::rowCount(const QModelIndex &parent) const { @@ -160,10 +160,10 @@ bool ImportsProxyModel::lessThan(const QModelIndex &left, const QModelIndex &rig * Imports Widget */ -ImportsWidget::ImportsWidget(MainWindow *main) : - ListDockWidget(main), - importsModel(new ImportsModel(&imports, this)), - importsProxyModel(new ImportsProxyModel(importsModel, this)) +ImportsWidget::ImportsWidget(MainWindow *main) + : ListDockWidget(main), + importsModel(new ImportsModel(&imports, this)), + importsProxyModel(new ImportsProxyModel(importsModel, this)) { setWindowTitle(tr("Imports")); setObjectName("ImportsWidget"); @@ -172,15 +172,12 @@ ImportsWidget::ImportsWidget(MainWindow *main) : // Sort by library name by default to create a solid context per each group of imports ui->treeView->sortByColumn(ImportsModel::LibraryColumn, Qt::AscendingOrder); QShortcut *toggle_shortcut = new QShortcut(widgetShortcuts["ImportsWidget"], main); - connect(toggle_shortcut, &QShortcut::activated, this, [=] (){ - toggleDockWidget(true); - } ); + connect(toggle_shortcut, &QShortcut::activated, this, [=]() { toggleDockWidget(true); }); connect(Core(), &CutterCore::codeRebased, this, &ImportsWidget::refreshImports); connect(Core(), &CutterCore::refreshAll, this, &ImportsWidget::refreshImports); - connect(Core(), &CutterCore::commentsChanged, this, [this]() { - qhelpers::emitColumnChanged(importsModel, ImportsModel::CommentColumn); - }); + connect(Core(), &CutterCore::commentsChanged, this, + [this]() { qhelpers::emitColumnChanged(importsModel, ImportsModel::CommentColumn); }); } ImportsWidget::~ImportsWidget() {} diff --git a/src/widgets/ImportsWidget.h b/src/widgets/ImportsWidget.h index e2e9b585..f440a2fa 100644 --- a/src/widgets/ImportsWidget.h +++ b/src/widgets/ImportsWidget.h @@ -25,25 +25,45 @@ class ImportsModel : public AddressableItemModel friend ImportsWidget; private: - const QRegularExpression banned = QRegularExpression(QStringLiteral( - "\\A(\\w\\.)*(system|strcpy|strcpyA|strcpyW|wcscpy|_tcscpy|_mbscpy|StrCpy|StrCpyA|StrCpyW|lstrcpy|lstrcpyA|lstrcpyW" - "|_tccpy|_mbccpy|_ftcscpy|strcat|strcatA|strcatW|wcscat|_tcscat|_mbscat|StrCat|StrCatA|StrCatW|lstrcat|lstrcatA|" - "lstrcatW|StrCatBuff|StrCatBuffA|StrCatBuffW|StrCatChainW|_tccat|_mbccat|_ftcscat|sprintfW|sprintfA|wsprintf|wsprintfW|" - "wsprintfA|sprintf|swprintf|_stprintf|wvsprintf|wvsprintfA|wvsprintfW|vsprintf|_vstprintf|vswprintf|strncpy|wcsncpy|" - "_tcsncpy|_mbsncpy|_mbsnbcpy|StrCpyN|StrCpyNA|StrCpyNW|StrNCpy|strcpynA|StrNCpyA|StrNCpyW|lstrcpyn|lstrcpynA|lstrcpynW|" - "strncat|wcsncat|_tcsncat|_mbsncat|_mbsnbcat|StrCatN|StrCatNA|StrCatNW|StrNCat|StrNCatA|StrNCatW|lstrncat|lstrcatnA|" - "lstrcatnW|lstrcatn|gets|_getts|_gettws|IsBadWritePtr|IsBadHugeWritePtr|IsBadReadPtr|IsBadHugeReadPtr|IsBadCodePtr|" - "IsBadStringPtr|memcpy|RtlCopyMemory|CopyMemory|wmemcpy|wnsprintf|wnsprintfA|wnsprintfW|_snwprintf|_snprintf|_sntprintf|" - "_vsnprintf|vsnprintf|_vsnwprintf|_vsntprintf|wvnsprintf|wvnsprintfA|wvnsprintfW|strtok|_tcstok|wcstok|_mbstok|makepath|" - "_tmakepath| _makepath|_wmakepath|_splitpath|_tsplitpath|_wsplitpath|scanf|wscanf|_tscanf|sscanf|swscanf|_stscanf|snscanf|" - "snwscanf|_sntscanf|_itoa|_itow|_i64toa|_i64tow|_ui64toa|_ui64tot|_ui64tow|_ultoa|_ultot|_ultow|CharToOem|CharToOemA|CharToOemW|" - "OemToChar|OemToCharA|OemToCharW|CharToOemBuffA|CharToOemBuffW|alloca|_alloca|strlen|wcslen|_mbslen|_mbstrlen|StrLen|lstrlen|" - "ChangeWindowMessageFilter)\\z" - )); + const QRegularExpression banned = QRegularExpression( + QStringLiteral("\\A(\\w\\.)*(system|strcpy|strcpyA|strcpyW|wcscpy|_tcscpy|_mbscpy|" + "StrCpy|StrCpyA|StrCpyW|lstrcpy|lstrcpyA|lstrcpyW" + "|_tccpy|_mbccpy|_ftcscpy|strcat|strcatA|strcatW|wcscat|_tcscat|_mbscat|" + "StrCat|StrCatA|StrCatW|lstrcat|lstrcatA|" + "lstrcatW|StrCatBuff|StrCatBuffA|StrCatBuffW|StrCatChainW|_tccat|_" + "mbccat|_ftcscat|sprintfW|sprintfA|wsprintf|wsprintfW|" + "wsprintfA|sprintf|swprintf|_stprintf|wvsprintf|wvsprintfA|wvsprintfW|" + "vsprintf|_vstprintf|vswprintf|strncpy|wcsncpy|" + "_tcsncpy|_mbsncpy|_mbsnbcpy|StrCpyN|StrCpyNA|StrCpyNW|StrNCpy|strcpynA|" + "StrNCpyA|StrNCpyW|lstrcpyn|lstrcpynA|lstrcpynW|" + "strncat|wcsncat|_tcsncat|_mbsncat|_mbsnbcat|StrCatN|StrCatNA|StrCatNW|" + "StrNCat|StrNCatA|StrNCatW|lstrncat|lstrcatnA|" + "lstrcatnW|lstrcatn|gets|_getts|_gettws|IsBadWritePtr|IsBadHugeWritePtr|" + "IsBadReadPtr|IsBadHugeReadPtr|IsBadCodePtr|" + "IsBadStringPtr|memcpy|RtlCopyMemory|CopyMemory|wmemcpy|wnsprintf|" + "wnsprintfA|wnsprintfW|_snwprintf|_snprintf|_sntprintf|" + "_vsnprintf|vsnprintf|_vsnwprintf|_vsntprintf|wvnsprintf|wvnsprintfA|" + "wvnsprintfW|strtok|_tcstok|wcstok|_mbstok|makepath|" + "_tmakepath| " + "_makepath|_wmakepath|_splitpath|_tsplitpath|_wsplitpath|scanf|wscanf|_" + "tscanf|sscanf|swscanf|_stscanf|snscanf|" + "snwscanf|_sntscanf|_itoa|_itow|_i64toa|_i64tow|_ui64toa|_ui64tot|_" + "ui64tow|_ultoa|_ultot|_ultow|CharToOem|CharToOemA|CharToOemW|" + "OemToChar|OemToCharA|OemToCharW|CharToOemBuffA|CharToOemBuffW|alloca|_" + "alloca|strlen|wcslen|_mbslen|_mbstrlen|StrLen|lstrlen|" + "ChangeWindowMessageFilter)\\z")); QList *imports; public: - enum Column { AddressColumn = 0, TypeColumn, LibraryColumn, NameColumn, SafetyColumn, CommentColumn, ColumnCount }; + enum Column { + AddressColumn = 0, + TypeColumn, + LibraryColumn, + NameColumn, + SafetyColumn, + CommentColumn, + ColumnCount + }; enum Role { ImportDescriptionRole = Qt::UserRole, AddressRole }; ImportsModel(QList *imports, QObject *parent = nullptr); @@ -57,7 +77,6 @@ public: RVA address(const QModelIndex &index) const override; QString name(const QModelIndex &index) const override; QString libname(const QModelIndex &index) const; - }; class ImportsProxyModel : public AddressableFilterProxyModel @@ -82,6 +101,7 @@ public: private slots: void refreshImports(); + private: ImportsModel *importsModel; ImportsProxyModel *importsProxyModel; diff --git a/src/widgets/ListDockWidget.cpp b/src/widgets/ListDockWidget.cpp index 42435961..e8e46ee1 100644 --- a/src/widgets/ListDockWidget.cpp +++ b/src/widgets/ListDockWidget.cpp @@ -8,11 +8,11 @@ #include #include -ListDockWidget::ListDockWidget(MainWindow *main, SearchBarPolicy searchBarPolicy) : - CutterDockWidget(main), - ui(new Ui::ListDockWidget), - tree(new CutterTreeWidget(this)), - searchBarPolicy(searchBarPolicy) +ListDockWidget::ListDockWidget(MainWindow *main, SearchBarPolicy searchBarPolicy) + : CutterDockWidget(main), + ui(new Ui::ListDockWidget), + tree(new CutterTreeWidget(this)), + searchBarPolicy(searchBarPolicy) { ui->setupUi(this); @@ -22,7 +22,8 @@ ListDockWidget::ListDockWidget(MainWindow *main, SearchBarPolicy searchBarPolicy if (searchBarPolicy != SearchBarPolicy::Hide) { // Ctrl-F to show/hide the filter entry QShortcut *searchShortcut = new QShortcut(QKeySequence::Find, this); - connect(searchShortcut, &QShortcut::activated, ui->quickFilterView, &QuickFilterView::showFilter); + connect(searchShortcut, &QShortcut::activated, ui->quickFilterView, + &QuickFilterView::showFilter); searchShortcut->setContext(Qt::WidgetWithChildrenShortcut); // Esc to clear the filter entry @@ -54,17 +55,13 @@ void ListDockWidget::setModels(AddressableFilterProxyModel *objectFilterProxyMod { this->objectFilterProxyModel = objectFilterProxyModel; - ui->treeView->setModel(objectFilterProxyModel); - - connect(ui->quickFilterView, &QuickFilterView::filterTextChanged, - objectFilterProxyModel, &QSortFilterProxyModel::setFilterWildcard); + connect(ui->quickFilterView, &QuickFilterView::filterTextChanged, objectFilterProxyModel, + &QSortFilterProxyModel::setFilterWildcard); connect(ui->quickFilterView, &QuickFilterView::filterClosed, ui->treeView, - static_cast(&QWidget::setFocus)); + static_cast(&QWidget::setFocus)); - - connect(ui->quickFilterView, &QuickFilterView::filterTextChanged, this, [this] { - tree->showItemsNumber(this->objectFilterProxyModel->rowCount()); - }); + connect(ui->quickFilterView, &QuickFilterView::filterTextChanged, this, + [this] { tree->showItemsNumber(this->objectFilterProxyModel->rowCount()); }); } diff --git a/src/widgets/ListDockWidget.h b/src/widgets/ListDockWidget.h index 4d8184c8..662714e8 100644 --- a/src/widgets/ListDockWidget.h +++ b/src/widgets/ListDockWidget.h @@ -20,7 +20,6 @@ namespace Ui { class ListDockWidget; } - class CUTTER_EXPORT ListDockWidget : public CutterDockWidget { Q_OBJECT @@ -32,14 +31,17 @@ public: Hide, }; - explicit ListDockWidget(MainWindow *main, SearchBarPolicy searchBarPolicy = SearchBarPolicy::ShowByDefault); + explicit ListDockWidget(MainWindow *main, + SearchBarPolicy searchBarPolicy = SearchBarPolicy::ShowByDefault); ~ListDockWidget() override; void showCount(bool show); + protected: void setModels(AddressableFilterProxyModel *objectFilterProxyModel); std::unique_ptr ui; + private: AddressableFilterProxyModel *objectFilterProxyModel = nullptr; CutterTreeWidget *tree; diff --git a/src/widgets/MemoryDockWidget.cpp b/src/widgets/MemoryDockWidget.cpp index 657ffb3d..ac1eef74 100644 --- a/src/widgets/MemoryDockWidget.cpp +++ b/src/widgets/MemoryDockWidget.cpp @@ -7,8 +7,7 @@ #include MemoryDockWidget::MemoryDockWidget(MemoryWidgetType type, MainWindow *parent) - : AddressableDockWidget(parent) - , mType(type) + : AddressableDockWidget(parent), mType(type) { if (parent) { parent->addMemoryDockWidget(this); diff --git a/src/widgets/MemoryDockWidget.h b/src/widgets/MemoryDockWidget.h index eb3c329e..51d0ca88 100644 --- a/src/widgets/MemoryDockWidget.h +++ b/src/widgets/MemoryDockWidget.h @@ -17,13 +17,10 @@ public: ~MemoryDockWidget() override {} bool tryRaiseMemoryWidget(); - MemoryWidgetType getType() const - { - return mType; - } + MemoryWidgetType getType() const { return mType; } bool eventFilter(QObject *object, QEvent *event) override; -private: +private: MemoryWidgetType mType; }; diff --git a/src/widgets/MemoryMapWidget.cpp b/src/widgets/MemoryMapWidget.cpp index a6f71684..bcf189c7 100644 --- a/src/widgets/MemoryMapWidget.cpp +++ b/src/widgets/MemoryMapWidget.cpp @@ -5,8 +5,7 @@ #include MemoryMapModel::MemoryMapModel(QList *memoryMaps, QObject *parent) - : AddressableItemModel(parent), - memoryMaps(memoryMaps) + : AddressableItemModel(parent), memoryMaps(memoryMaps) { } @@ -87,17 +86,17 @@ MemoryProxyModel::MemoryProxyModel(MemoryMapModel *sourceModel, QObject *parent) bool MemoryProxyModel::filterAcceptsRow(int row, const QModelIndex &parent) const { QModelIndex index = sourceModel()->index(row, 0, parent); - MemoryMapDescription item = index.data( - MemoryMapModel::MemoryDescriptionRole).value(); + MemoryMapDescription item = + index.data(MemoryMapModel::MemoryDescriptionRole).value(); return item.name.contains(filterRegExp()); } bool MemoryProxyModel::lessThan(const QModelIndex &left, const QModelIndex &right) const { - MemoryMapDescription leftMemMap = left.data( - MemoryMapModel::MemoryDescriptionRole).value(); - MemoryMapDescription rightMemMap = right.data( - MemoryMapModel::MemoryDescriptionRole).value(); + MemoryMapDescription leftMemMap = + left.data(MemoryMapModel::MemoryDescriptionRole).value(); + MemoryMapDescription rightMemMap = + right.data(MemoryMapModel::MemoryDescriptionRole).value(); switch (left.column()) { case MemoryMapModel::AddrStartColumn: @@ -109,7 +108,8 @@ bool MemoryProxyModel::lessThan(const QModelIndex &left, const QModelIndex &righ case MemoryMapModel::PermColumn: return leftMemMap.permission < rightMemMap.permission; case MemoryMapModel::CommentColumn: - return Core()->getCommentAt(leftMemMap.addrStart) < Core()->getCommentAt(rightMemMap.addrStart); + return Core()->getCommentAt(leftMemMap.addrStart) + < Core()->getCommentAt(rightMemMap.addrStart); default: break; } @@ -117,8 +117,8 @@ bool MemoryProxyModel::lessThan(const QModelIndex &left, const QModelIndex &righ return leftMemMap.addrStart < rightMemMap.addrStart; } -MemoryMapWidget::MemoryMapWidget(MainWindow *main) : - ListDockWidget(main, ListDockWidget::SearchBarPolicy::HideByDefault) +MemoryMapWidget::MemoryMapWidget(MainWindow *main) + : ListDockWidget(main, ListDockWidget::SearchBarPolicy::HideByDefault) { setWindowTitle(tr("Memory Map")); setObjectName("MemoryMapWidget"); @@ -128,15 +128,12 @@ MemoryMapWidget::MemoryMapWidget(MainWindow *main) : setModels(memoryProxyModel); ui->treeView->sortByColumn(MemoryMapModel::AddrStartColumn, Qt::AscendingOrder); - refreshDeferrer = createRefreshDeferrer([this]() { - refreshMemoryMap(); - }); + refreshDeferrer = createRefreshDeferrer([this]() { refreshMemoryMap(); }); connect(Core(), &CutterCore::refreshAll, this, &MemoryMapWidget::refreshMemoryMap); connect(Core(), &CutterCore::registersChanged, this, &MemoryMapWidget::refreshMemoryMap); - connect(Core(), &CutterCore::commentsChanged, this, [this]() { - qhelpers::emitColumnChanged(memoryModel, MemoryMapModel::CommentColumn); - }); + connect(Core(), &CutterCore::commentsChanged, this, + [this]() { qhelpers::emitColumnChanged(memoryModel, MemoryMapModel::CommentColumn); }); showCount(false); } diff --git a/src/widgets/MemoryMapWidget.h b/src/widgets/MemoryMapWidget.h index e5b64ef2..f50273db 100644 --- a/src/widgets/MemoryMapWidget.h +++ b/src/widgets/MemoryMapWidget.h @@ -17,12 +17,10 @@ namespace Ui { class MemoryMapWidget; } - class MainWindow; class QTreeWidgetItem; - -class MemoryMapModel: public AddressableItemModel +class MemoryMapModel : public AddressableItemModel { Q_OBJECT @@ -32,7 +30,14 @@ private: QList *memoryMaps; public: - enum Column { AddrStartColumn = 0, AddrEndColumn, NameColumn, PermColumn, CommentColumn, ColumnCount }; + enum Column { + AddrStartColumn = 0, + AddrEndColumn, + NameColumn, + PermColumn, + CommentColumn, + ColumnCount + }; enum Role { MemoryDescriptionRole = Qt::UserRole }; MemoryMapModel(QList *memoryMaps, QObject *parent = nullptr); @@ -41,13 +46,12 @@ public: int columnCount(const QModelIndex &parent = QModelIndex()) const override; QVariant data(const QModelIndex &index, int role) const override; - QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; + QVariant headerData(int section, Qt::Orientation orientation, + int role = Qt::DisplayRole) const override; RVA address(const QModelIndex &index) const override; }; - - class MemoryProxyModel : public AddressableFilterProxyModel { Q_OBJECT @@ -60,8 +64,6 @@ protected: bool lessThan(const QModelIndex &left, const QModelIndex &right) const override; }; - - class MemoryMapWidget : public ListDockWidget { Q_OBJECT diff --git a/src/widgets/Omnibar.cpp b/src/widgets/Omnibar.cpp index 369b0963..6ba22657 100644 --- a/src/widgets/Omnibar.cpp +++ b/src/widgets/Omnibar.cpp @@ -7,10 +7,7 @@ #include #include - -Omnibar::Omnibar(MainWindow *main, QWidget *parent) : - QLineEdit(parent), - main(main) +Omnibar::Omnibar(MainWindow *main, QWidget *parent) : QLineEdit(parent), main(main) { // QLineEdit basic features this->setMinimumHeight(16); diff --git a/src/widgets/Omnibar.h b/src/widgets/Omnibar.h index 0cc51be0..b3dc05e3 100644 --- a/src/widgets/Omnibar.h +++ b/src/widgets/Omnibar.h @@ -24,8 +24,8 @@ public slots: private: void setupCompleter(); - MainWindow *main; - QStringList flags; + MainWindow *main; + QStringList flags; }; #endif // OMNIBAR_H diff --git a/src/widgets/OverviewView.cpp b/src/widgets/OverviewView.cpp index 1a7b5b11..18e393db 100644 --- a/src/widgets/OverviewView.cpp +++ b/src/widgets/OverviewView.cpp @@ -7,8 +7,7 @@ #include "common/Configuration.h" #include "common/TempConfig.h" -OverviewView::OverviewView(QWidget *parent) - : GraphView(parent) +OverviewView::OverviewView(QWidget *parent) : GraphView(parent) { connect(Config(), &Configuration::colorsUpdated, this, &OverviewView::colorsUpdatedSlot); colorsUpdatedSlot(); @@ -31,12 +30,10 @@ void OverviewView::centreRect() { qreal w = rangeRect.width(); qreal h = rangeRect.height(); - initialDiff = QPointF(w / 2, h / 2); + initialDiff = QPointF(w / 2, h / 2); } -OverviewView::~OverviewView() -{ -} +OverviewView::~OverviewView() {} void OverviewView::scaleAndCenter() { @@ -92,14 +89,15 @@ void OverviewView::mousePressEvent(QMouseEvent *event) { mouseActive = true; if (rangeRect.contains(event->pos())) { - initialDiff = QPointF(event->localPos().x() - rangeRect.x(), event->localPos().y() - rangeRect.y()); + initialDiff = QPointF(event->localPos().x() - rangeRect.x(), + event->localPos().y() - rangeRect.y()); } else { qreal w = rangeRect.width(); qreal h = rangeRect.height(); qreal x = event->localPos().x() - w / 2; qreal y = event->localPos().y() - h / 2; rangeRect = QRectF(x, y, w, h); - initialDiff = QPointF(w / 2, h / 2); + initialDiff = QPointF(w / 2, h / 2); viewport()->update(); emit mouseMoved(); } @@ -134,7 +132,7 @@ GraphView::EdgeConfiguration OverviewView::edgeConfiguration(GraphView::GraphBlo { Q_UNUSED(interactive) EdgeConfiguration ec; - auto baseEcIt = edgeConfigurations.find({from.entry, to->entry}); + auto baseEcIt = edgeConfigurations.find({ from.entry, to->entry }); if (baseEcIt != edgeConfigurations.end()) ec = baseEcIt->second; ec.width_scale = 1.0 / getViewScale(); diff --git a/src/widgets/OverviewView.h b/src/widgets/OverviewView.h index 27053289..f2ed2fe3 100644 --- a/src/widgets/OverviewView.h +++ b/src/widgets/OverviewView.h @@ -140,7 +140,7 @@ private: DisassemblerGraphView::EdgeConfigurationMapping edgeConfigurations; public: - QRectF getRangeRect() { return rangeRect; } + QRectF getRangeRect() { return rangeRect; } void setRangeRect(QRectF rect); }; diff --git a/src/widgets/OverviewWidget.cpp b/src/widgets/OverviewWidget.cpp index 9b7c0b5a..e39dfcc1 100644 --- a/src/widgets/OverviewWidget.cpp +++ b/src/widgets/OverviewWidget.cpp @@ -3,8 +3,7 @@ #include "GraphWidget.h" #include "OverviewView.h" -OverviewWidget::OverviewWidget(MainWindow *main) : - CutterDockWidget(main) +OverviewWidget::OverviewWidget(MainWindow *main) : CutterDockWidget(main) { setWindowTitle("Graph Overview"); setObjectName("Graph Overview"); @@ -15,17 +14,15 @@ OverviewWidget::OverviewWidget(MainWindow *main) : connect(graphView, &OverviewView::mouseMoved, this, &OverviewWidget::updateTargetView); - graphDataRefreshDeferrer = createRefreshDeferrer([this]() { - updateGraphData(); - }); + graphDataRefreshDeferrer = createRefreshDeferrer([this]() { updateGraphData(); }); // Zoom shortcuts QShortcut *shortcut_zoom_in = new QShortcut(QKeySequence(Qt::Key_Plus), this); shortcut_zoom_in->setContext(Qt::WidgetWithChildrenShortcut); - connect(shortcut_zoom_in, &QShortcut::activated, this, [this](){ zoomTarget(1); }); + connect(shortcut_zoom_in, &QShortcut::activated, this, [this]() { zoomTarget(1); }); QShortcut *shortcut_zoom_out = new QShortcut(QKeySequence(Qt::Key_Minus), this); shortcut_zoom_out->setContext(Qt::WidgetWithChildrenShortcut); - connect(shortcut_zoom_out, &QShortcut::activated, this, [this](){ zoomTarget(-1); }); + connect(shortcut_zoom_out, &QShortcut::activated, this, [this]() { zoomTarget(-1); }); } OverviewWidget::~OverviewWidget() {} @@ -56,9 +53,9 @@ void OverviewWidget::setIsAvailable(bool isAvailable) return; } this->isAvailable = isAvailable; - if(!isAvailable) { + if (!isAvailable) { hide(); - } else if(userOpened) { + } else if (userOpened) { show(); } emit isAvailableChanged(isAvailable); @@ -87,18 +84,27 @@ void OverviewWidget::setTargetGraphWidget(GraphWidget *widget) return; } if (targetGraphWidget) { - disconnect(targetGraphWidget->getGraphView(), &DisassemblerGraphView::viewRefreshed, this, &OverviewWidget::updateGraphData); - disconnect(targetGraphWidget->getGraphView(), &DisassemblerGraphView::resized, this, &OverviewWidget::updateRangeRect); - disconnect(targetGraphWidget->getGraphView(), &GraphView::viewOffsetChanged, this, &OverviewWidget::updateRangeRect); - disconnect(targetGraphWidget->getGraphView(), &GraphView::viewScaleChanged, this, &OverviewWidget::updateRangeRect); - disconnect(targetGraphWidget, &GraphWidget::graphClosed, this, &OverviewWidget::targetClosed); + disconnect(targetGraphWidget->getGraphView(), &DisassemblerGraphView::viewRefreshed, this, + &OverviewWidget::updateGraphData); + disconnect(targetGraphWidget->getGraphView(), &DisassemblerGraphView::resized, this, + &OverviewWidget::updateRangeRect); + disconnect(targetGraphWidget->getGraphView(), &GraphView::viewOffsetChanged, this, + &OverviewWidget::updateRangeRect); + disconnect(targetGraphWidget->getGraphView(), &GraphView::viewScaleChanged, this, + &OverviewWidget::updateRangeRect); + disconnect(targetGraphWidget, &GraphWidget::graphClosed, this, + &OverviewWidget::targetClosed); } targetGraphWidget = widget; if (targetGraphWidget) { - connect(targetGraphWidget->getGraphView(), &DisassemblerGraphView::viewRefreshed, this, &OverviewWidget::updateGraphData); - connect(targetGraphWidget->getGraphView(), &DisassemblerGraphView::resized, this, &OverviewWidget::updateRangeRect); - connect(targetGraphWidget->getGraphView(), &GraphView::viewOffsetChanged, this, &OverviewWidget::updateRangeRect); - connect(targetGraphWidget->getGraphView(), &GraphView::viewScaleChanged, this, &OverviewWidget::updateRangeRect); + connect(targetGraphWidget->getGraphView(), &DisassemblerGraphView::viewRefreshed, this, + &OverviewWidget::updateGraphData); + connect(targetGraphWidget->getGraphView(), &DisassemblerGraphView::resized, this, + &OverviewWidget::updateRangeRect); + connect(targetGraphWidget->getGraphView(), &GraphView::viewOffsetChanged, this, + &OverviewWidget::updateRangeRect); + connect(targetGraphWidget->getGraphView(), &GraphView::viewScaleChanged, this, + &OverviewWidget::updateRangeRect); connect(targetGraphWidget, &GraphWidget::graphClosed, this, &OverviewWidget::targetClosed); } updateGraphData(); @@ -143,7 +149,7 @@ void OverviewWidget::updateGraphData() graphView->currentFcnAddr = targetGraphWidget->getGraphView()->currentFcnAddr; auto &mainGraphView = *targetGraphWidget->getGraphView(); graphView->setData(mainGraphView.getWidth(), mainGraphView.getHeight(), - mainGraphView.getBlocks(), mainGraphView.getEdgeConfigurations()); + mainGraphView.getBlocks(), mainGraphView.getEdgeConfigurations()); } else { graphView->currentFcnAddr = RVA_INVALID; graphView->setData(0, 0, {}, {}); @@ -151,7 +157,8 @@ void OverviewWidget::updateGraphData() } } -void OverviewWidget::updateRangeRect() { +void OverviewWidget::updateRangeRect() +{ if (targetGraphWidget) { qreal curScale = graphView->getViewScale(); qreal baseScale = targetGraphWidget->getGraphView()->getViewScale(); diff --git a/src/widgets/OverviewWidget.h b/src/widgets/OverviewWidget.h index f90825e3..017d444d 100644 --- a/src/widgets/OverviewWidget.h +++ b/src/widgets/OverviewWidget.h @@ -43,7 +43,8 @@ private slots: void updateTargetView(); /** - * @brief update the content of the graph (blocks, edges) in the contained graphView from the target widget + * @brief update the content of the graph (blocks, edges) in the contained graphView from the + * target widget */ void updateGraphData(); @@ -77,7 +78,7 @@ public: /** * @brief whether this widget makes sense to be show, i.e. the menu entry should be enabled */ - bool getIsAvailable() const { return isAvailable; } + bool getIsAvailable() const { return isAvailable; } /** * @brief whether this widget is desired to be shown in general @@ -85,9 +86,9 @@ public: * Will be false when the user closed the overview explicitly. * Also corresponds to the checked state of the menu entry for this widget. */ - bool getUserOpened() const { return userOpened; } + bool getUserOpened() const { return userOpened; } - OverviewView *getGraphView() const { return graphView; } + OverviewView *getGraphView() const { return graphView; } void wheelEvent(QWheelEvent *event) override; }; diff --git a/src/widgets/ProcessesWidget.cpp b/src/widgets/ProcessesWidget.cpp index da0ac6c4..34896a4c 100644 --- a/src/widgets/ProcessesWidget.cpp +++ b/src/widgets/ProcessesWidget.cpp @@ -16,9 +16,8 @@ enum ColumnIndex { COLUMN_PATH, }; -ProcessesWidget::ProcessesWidget(MainWindow *main) : - CutterDockWidget(main), - ui(new Ui::ProcessesWidget) +ProcessesWidget::ProcessesWidget(MainWindow *main) + : CutterDockWidget(main), ui(new Ui::ProcessesWidget) { ui->setupUi(this); @@ -38,7 +37,8 @@ ProcessesWidget::ProcessesWidget(MainWindow *main) : // CTRL+F switches to the filter view and opens it in case it's hidden QShortcut *searchShortcut = new QShortcut(QKeySequence::Find, this); - connect(searchShortcut, &QShortcut::activated, ui->quickFilterView, &QuickFilterView::showFilter); + connect(searchShortcut, &QShortcut::activated, ui->quickFilterView, + &QuickFilterView::showFilter); searchShortcut->setContext(Qt::WidgetWithChildrenShortcut); // ESC switches back to the processes table and clears the buffer @@ -49,9 +49,7 @@ ProcessesWidget::ProcessesWidget(MainWindow *main) : }); clearShortcut->setContext(Qt::WidgetWithChildrenShortcut); - refreshDeferrer = createRefreshDeferrer([this]() { - updateContents(); - }); + refreshDeferrer = createRefreshDeferrer([this]() { updateContents(); }); connect(ui->quickFilterView, &QuickFilterView::filterTextChanged, modelFilter, &ProcessesFilterModel::setFilterWildcard); @@ -146,7 +144,8 @@ void ProcessesWidget::setProcessesGrid() } modelFilter->setSourceModel(modelProcesses); - ui->viewProcesses->resizeColumnsToContents();; + ui->viewProcesses->resizeColumnsToContents(); + ; } void ProcessesWidget::fontsUpdatedSlot() @@ -181,8 +180,7 @@ void ProcessesWidget::onActivated(const QModelIndex &index) updateContents(); } -ProcessesFilterModel::ProcessesFilterModel(QObject *parent) - : QSortFilterProxyModel(parent) +ProcessesFilterModel::ProcessesFilterModel(QObject *parent) : QSortFilterProxyModel(parent) { setFilterCaseSensitivity(Qt::CaseInsensitive); setSortCaseSensitivity(Qt::CaseInsensitive); diff --git a/src/widgets/QuickFilterView.cpp b/src/widgets/QuickFilterView.cpp index ff0ab050..f6bb88a1 100644 --- a/src/widgets/QuickFilterView.cpp +++ b/src/widgets/QuickFilterView.cpp @@ -2,17 +2,15 @@ #include "QuickFilterView.h" #include "ui_QuickFilterView.h" -QuickFilterView::QuickFilterView(QWidget *parent, bool defaultOn) : - QWidget(parent), - ui(new Ui::QuickFilterView()) +QuickFilterView::QuickFilterView(QWidget *parent, bool defaultOn) + : QWidget(parent), ui(new Ui::QuickFilterView()) { ui->setupUi(this); connect(ui->closeFilterButton, &QAbstractButton::clicked, this, &QuickFilterView::closeFilter); - connect(ui->filterLineEdit, &QLineEdit::textChanged, this, [this](const QString & text) { - emit filterTextChanged(text); - }); + connect(ui->filterLineEdit, &QLineEdit::textChanged, this, + [this](const QString &text) { emit filterTextChanged(text); }); if (!defaultOn) { closeFilter(); @@ -21,7 +19,6 @@ QuickFilterView::QuickFilterView(QWidget *parent, bool defaultOn) : QuickFilterView::~QuickFilterView() {} - void QuickFilterView::showFilter() { show(); diff --git a/src/widgets/QuickFilterView.h b/src/widgets/QuickFilterView.h index 9fb47cbc..7c92c3a3 100644 --- a/src/widgets/QuickFilterView.h +++ b/src/widgets/QuickFilterView.h @@ -33,4 +33,4 @@ private: std::unique_ptr ui; }; -#endif //QUICKFILTERVIEW_H +#endif // QUICKFILTERVIEW_H diff --git a/src/widgets/RegisterRefsWidget.cpp b/src/widgets/RegisterRefsWidget.cpp index 239b79dd..232db549 100644 --- a/src/widgets/RegisterRefsWidget.cpp +++ b/src/widgets/RegisterRefsWidget.cpp @@ -9,8 +9,7 @@ #include RegisterRefModel::RegisterRefModel(QList *registerRefs, QObject *parent) - : QAbstractListModel(parent), - registerRefs(registerRefs) + : QAbstractListModel(parent), registerRefs(registerRefs) { } @@ -89,17 +88,17 @@ RegisterRefProxyModel::RegisterRefProxyModel(RegisterRefModel *sourceModel, QObj bool RegisterRefProxyModel::filterAcceptsRow(int row, const QModelIndex &parent) const { QModelIndex index = sourceModel()->index(row, 0, parent); - RegisterRefDescription item = index.data( - RegisterRefModel::RegisterRefDescriptionRole).value(); + RegisterRefDescription item = index.data(RegisterRefModel::RegisterRefDescriptionRole) + .value(); return item.reg.contains(filterRegExp()); } bool RegisterRefProxyModel::lessThan(const QModelIndex &left, const QModelIndex &right) const { - RegisterRefDescription leftRegRef = left.data( - RegisterRefModel::RegisterRefDescriptionRole).value(); - RegisterRefDescription rightRegRef = right.data( - RegisterRefModel::RegisterRefDescriptionRole).value(); + RegisterRefDescription leftRegRef = + left.data(RegisterRefModel::RegisterRefDescriptionRole).value(); + RegisterRefDescription rightRegRef = right.data(RegisterRefModel::RegisterRefDescriptionRole) + .value(); switch (left.column()) { case RegisterRefModel::RegColumn: @@ -109,7 +108,8 @@ bool RegisterRefProxyModel::lessThan(const QModelIndex &left, const QModelIndex case RegisterRefModel::ValueColumn: return leftRegRef.value < rightRegRef.value; case RegisterRefModel::CommentColumn: - return Core()->getCommentAt(Core()->math(leftRegRef.value)) < Core()->getCommentAt(Core()->math(rightRegRef.value)); + return Core()->getCommentAt(Core()->math(leftRegRef.value)) + < Core()->getCommentAt(Core()->math(rightRegRef.value)); default: break; } @@ -117,11 +117,11 @@ bool RegisterRefProxyModel::lessThan(const QModelIndex &left, const QModelIndex return leftRegRef.reg < rightRegRef.reg; } -RegisterRefsWidget::RegisterRefsWidget(MainWindow *main) : - CutterDockWidget(main), - ui(new Ui::RegisterRefsWidget), - tree(new CutterTreeWidget(this)), - addressableItemContextMenu(this, main) +RegisterRefsWidget::RegisterRefsWidget(MainWindow *main) + : CutterDockWidget(main), + ui(new Ui::RegisterRefsWidget), + tree(new CutterTreeWidget(this)), + addressableItemContextMenu(this, main) { ui->setupUi(this); @@ -141,42 +141,37 @@ RegisterRefsWidget::RegisterRefsWidget(MainWindow *main) : addressableItemContextMenu.addAction(actionCopyRef); addActions(addressableItemContextMenu.actions()); - connect(ui->registerRefTreeView->selectionModel(), &QItemSelectionModel::currentChanged, - this, &RegisterRefsWidget::onCurrentChanged); + connect(ui->registerRefTreeView->selectionModel(), &QItemSelectionModel::currentChanged, this, + &RegisterRefsWidget::onCurrentChanged); - refreshDeferrer = createRefreshDeferrer([this](){ - refreshRegisterRef(); - }); + refreshDeferrer = createRefreshDeferrer([this]() { refreshRegisterRef(); }); // Ctrl-F to show/hide the filter entry QShortcut *search_shortcut = new QShortcut(QKeySequence::Find, this); - connect(search_shortcut, &QShortcut::activated, ui->quickFilterView, &QuickFilterView::showFilter); + connect(search_shortcut, &QShortcut::activated, ui->quickFilterView, + &QuickFilterView::showFilter); search_shortcut->setContext(Qt::WidgetWithChildrenShortcut); - connect(ui->quickFilterView, &QuickFilterView::filterTextChanged, - registerRefProxyModel, &QSortFilterProxyModel::setFilterWildcard); - connect(ui->quickFilterView, &QuickFilterView::filterClosed, ui->registerRefTreeView, [this](){ - ui->registerRefTreeView->setFocus(); - }); + connect(ui->quickFilterView, &QuickFilterView::filterTextChanged, registerRefProxyModel, + &QSortFilterProxyModel::setFilterWildcard); + connect(ui->quickFilterView, &QuickFilterView::filterClosed, ui->registerRefTreeView, + [this]() { ui->registerRefTreeView->setFocus(); }); setScrollMode(); connect(Core(), &CutterCore::refreshAll, this, &RegisterRefsWidget::refreshRegisterRef); connect(Core(), &CutterCore::registersChanged, this, &RegisterRefsWidget::refreshRegisterRef); connect(Core(), &CutterCore::commentsChanged, this, [this]() { qhelpers::emitColumnChanged(registerRefModel, RegisterRefModel::CommentColumn); }); - connect(actionCopyValue, &QAction::triggered, this, [this] () { - copyClip(RegisterRefModel::ValueColumn); - }); - connect(actionCopyRef, &QAction::triggered, this, [this] () { - copyClip(RegisterRefModel::RefColumn); - }); + connect(actionCopyValue, &QAction::triggered, this, + [this]() { copyClip(RegisterRefModel::ValueColumn); }); + connect(actionCopyRef, &QAction::triggered, this, + [this]() { copyClip(RegisterRefModel::RefColumn); }); ui->registerRefTreeView->setContextMenuPolicy(Qt::CustomContextMenu); - connect(ui->registerRefTreeView, &QMenu::customContextMenuRequested, - this, &RegisterRefsWidget::customMenuRequested); + connect(ui->registerRefTreeView, &QMenu::customContextMenuRequested, this, + &RegisterRefsWidget::customMenuRequested); - connect(ui->quickFilterView, &QuickFilterView::filterTextChanged, this, [this] { - tree->showItemsNumber(registerRefProxyModel->rowCount()); - }); + connect(ui->quickFilterView, &QuickFilterView::filterTextChanged, this, + [this] { tree->showItemsNumber(registerRefProxyModel->rowCount()); }); } RegisterRefsWidget::~RegisterRefsWidget() = default; @@ -217,8 +212,8 @@ void RegisterRefsWidget::setScrollMode() void RegisterRefsWidget::on_registerRefTreeView_doubleClicked(const QModelIndex &index) { - RegisterRefDescription item = index.data( - RegisterRefModel::RegisterRefDescriptionRole).value(); + RegisterRefDescription item = index.data(RegisterRefModel::RegisterRefDescriptionRole) + .value(); Core()->seekAndShow(item.value); } @@ -238,7 +233,9 @@ void RegisterRefsWidget::onCurrentChanged(const QModelIndex ¤t, const QMod if (currentIndex.column() != RegisterRefModel::RefColumn) { offsetString = currentIndex.data().toString(); } else { - offsetString = currentIndex.sibling(currentIndex.row(), RegisterRefModel::ValueColumn).data().toString(); + offsetString = currentIndex.sibling(currentIndex.row(), RegisterRefModel::ValueColumn) + .data() + .toString(); } RVA offset = Core()->math(offsetString); @@ -248,8 +245,11 @@ void RegisterRefsWidget::onCurrentChanged(const QModelIndex ¤t, const QMod void RegisterRefsWidget::copyClip(int column) { int row = ui->registerRefTreeView->selectionModel()->currentIndex().row(); - QString value = ui->registerRefTreeView->selectionModel()->currentIndex().sibling(row, - column).data().toString(); + QString value = ui->registerRefTreeView->selectionModel() + ->currentIndex() + .sibling(row, column) + .data() + .toString(); QClipboard *clipboard = QApplication::clipboard(); clipboard->setText(value); } diff --git a/src/widgets/RegisterRefsWidget.h b/src/widgets/RegisterRefsWidget.h index cc93725b..d622f0ef 100644 --- a/src/widgets/RegisterRefsWidget.h +++ b/src/widgets/RegisterRefsWidget.h @@ -18,18 +18,18 @@ namespace Ui { class RegisterRefsWidget; } - class MainWindow; class QTreeWidgetItem; -struct RegisterRefDescription { +struct RegisterRefDescription +{ QString reg; QString value; RefDescription refDesc; }; Q_DECLARE_METATYPE(RegisterRefDescription) -class RegisterRefModel: public QAbstractListModel +class RegisterRefModel : public QAbstractListModel { Q_OBJECT @@ -63,7 +63,6 @@ protected: bool lessThan(const QModelIndex &left, const QModelIndex &right) const override; }; - class RegisterRefsWidget : public CutterDockWidget { Q_OBJECT diff --git a/src/widgets/RegistersWidget.cpp b/src/widgets/RegistersWidget.cpp index 98202d60..1ff2703e 100644 --- a/src/widgets/RegistersWidget.cpp +++ b/src/widgets/RegistersWidget.cpp @@ -8,21 +8,17 @@ #include #include -RegistersWidget::RegistersWidget(MainWindow *main) : - CutterDockWidget(main), - ui(new Ui::RegistersWidget), - addressContextMenu(this, main) +RegistersWidget::RegistersWidget(MainWindow *main) + : CutterDockWidget(main), ui(new Ui::RegistersWidget), addressContextMenu(this, main) { ui->setupUi(this); // setup register layout registerLayout->setVerticalSpacing(0); - registerLayout->setAlignment(Qt::AlignLeft | Qt::AlignTop) ; + registerLayout->setAlignment(Qt::AlignLeft | Qt::AlignTop); ui->verticalLayout->addLayout(registerLayout); - refreshDeferrer = createRefreshDeferrer([this]() { - updateContents(); - }); + refreshDeferrer = createRefreshDeferrer([this]() { updateContents(); }); connect(Core(), &CutterCore::refreshAll, this, &RegistersWidget::updateContents); connect(Core(), &CutterCore::registersChanged, this, &RegistersWidget::updateContents); @@ -67,17 +63,20 @@ void RegistersWidget::setRegisterGrid() registerEditValue->setMaximumWidth(140); registerEditValue->setFont(Config()->getFont()); registerLabel->setContextMenuPolicy(Qt::CustomContextMenu); - connect(registerLabel, &QWidget::customContextMenuRequested, this, [this, registerEditValue, registerLabel](QPoint p){ - openContextMenu(registerLabel->mapToGlobal(p), registerEditValue->text()); - }); + connect(registerLabel, &QWidget::customContextMenuRequested, this, + [this, registerEditValue, registerLabel](QPoint p) { + openContextMenu(registerLabel->mapToGlobal(p), registerEditValue->text()); + }); registerEditValue->setContextMenuPolicy(Qt::CustomContextMenu); - connect(registerEditValue, &QWidget::customContextMenuRequested, this, [this, registerEditValue](QPoint p){ - openContextMenu(registerEditValue->mapToGlobal(p), registerEditValue->text()); - }); + connect(registerEditValue, &QWidget::customContextMenuRequested, this, + [this, registerEditValue](QPoint p) { + openContextMenu(registerEditValue->mapToGlobal(p), + registerEditValue->text()); + }); // add label and register value to grid registerLayout->addWidget(registerLabel, i, col); registerLayout->addWidget(registerEditValue, i, col + 1); - connect(registerEditValue, &QLineEdit::editingFinished, [ = ]() { + connect(registerEditValue, &QLineEdit::editingFinished, [=]() { QString regNameString = registerLabel->text(); QString regValueString = registerEditValue->text(); Core()->setRegister(regNameString, regValueString); diff --git a/src/widgets/RelocsWidget.cpp b/src/widgets/RelocsWidget.cpp index 81e96740..2d8118bc 100644 --- a/src/widgets/RelocsWidget.cpp +++ b/src/widgets/RelocsWidget.cpp @@ -6,10 +6,10 @@ #include #include -RelocsModel::RelocsModel(QList *relocs, QObject *parent) : - AddressableItemModel(parent), - relocs(relocs) -{} +RelocsModel::RelocsModel(QList *relocs, QObject *parent) + : AddressableItemModel(parent), relocs(relocs) +{ +} int RelocsModel::rowCount(const QModelIndex &parent) const { @@ -119,10 +119,10 @@ bool RelocsProxyModel::lessThan(const QModelIndex &left, const QModelIndex &righ return false; } -RelocsWidget::RelocsWidget(MainWindow *main) : - ListDockWidget(main), - relocsModel(new RelocsModel(&relocs, this)), - relocsProxyModel(new RelocsProxyModel(relocsModel, this)) +RelocsWidget::RelocsWidget(MainWindow *main) + : ListDockWidget(main), + relocsModel(new RelocsModel(&relocs, this)), + relocsProxyModel(new RelocsProxyModel(relocsModel, this)) { setWindowTitle(tr("Relocs")); setObjectName("RelocsWidget"); @@ -132,9 +132,8 @@ RelocsWidget::RelocsWidget(MainWindow *main) : connect(Core(), &CutterCore::codeRebased, this, &RelocsWidget::refreshRelocs); connect(Core(), &CutterCore::refreshAll, this, &RelocsWidget::refreshRelocs); - connect(Core(), &CutterCore::commentsChanged, this, [this]() { - qhelpers::emitColumnChanged(relocsModel, RelocsModel::CommentColumn); - }); + connect(Core(), &CutterCore::commentsChanged, this, + [this]() { qhelpers::emitColumnChanged(relocsModel, RelocsModel::CommentColumn); }); } RelocsWidget::~RelocsWidget() {} diff --git a/src/widgets/ResourcesWidget.cpp b/src/widgets/ResourcesWidget.cpp index 1efec8cc..ec4e694f 100644 --- a/src/widgets/ResourcesWidget.cpp +++ b/src/widgets/ResourcesWidget.cpp @@ -5,8 +5,7 @@ #include ResourcesModel::ResourcesModel(QList *resources, QObject *parent) - : AddressableItemModel(parent), - resources(resources) + : AddressableItemModel(parent), resources(resources) { } @@ -101,8 +100,8 @@ RVA ResourcesModel::address(const QModelIndex &index) const return res.vaddr; } -ResourcesWidget::ResourcesWidget(MainWindow *main) : - ListDockWidget(main, ListDockWidget::SearchBarPolicy::HideByDefault) +ResourcesWidget::ResourcesWidget(MainWindow *main) + : ListDockWidget(main, ListDockWidget::SearchBarPolicy::HideByDefault) { setObjectName("ResourcesWidget"); @@ -119,9 +118,8 @@ ResourcesWidget::ResourcesWidget(MainWindow *main) : this->setWindowTitle(tr("Resources")); connect(Core(), &CutterCore::refreshAll, this, &ResourcesWidget::refreshResources); - connect(Core(), &CutterCore::commentsChanged, this, [this]() { - qhelpers::emitColumnChanged(model, ResourcesModel::COMMENT); - }); + connect(Core(), &CutterCore::commentsChanged, this, + [this]() { qhelpers::emitColumnChanged(model, ResourcesModel::COMMENT); }); } void ResourcesWidget::refreshResources() diff --git a/src/widgets/ResourcesWidget.h b/src/widgets/ResourcesWidget.h index 36461b9d..0523400f 100644 --- a/src/widgets/ResourcesWidget.h +++ b/src/widgets/ResourcesWidget.h @@ -7,7 +7,6 @@ #include "common/AddressableItemModel.h" #include "widgets/ListDockWidget.h" - class MainWindow; class ResourcesWidget; diff --git a/src/widgets/RizinGraphWidget.cpp b/src/widgets/RizinGraphWidget.cpp index a8705b29..a0b88e15 100644 --- a/src/widgets/RizinGraphWidget.cpp +++ b/src/widgets/RizinGraphWidget.cpp @@ -6,30 +6,29 @@ #include RizinGraphWidget::RizinGraphWidget(MainWindow *main) - : CutterDockWidget(main) - , ui(new Ui::RizinGraphWidget) - , graphView(new GenericRizinGraphView(this, main)) + : CutterDockWidget(main), + ui(new Ui::RizinGraphWidget), + graphView(new GenericRizinGraphView(this, main)) { ui->setupUi(this); ui->verticalLayout->addWidget(graphView); - connect(ui->refreshButton, &QPushButton::pressed, this, [this]() { - graphView->refreshView(); - }); - struct GraphType { + connect(ui->refreshButton, &QPushButton::pressed, this, [this]() { graphView->refreshView(); }); + struct GraphType + { QChar commandChar; QString label; } types[] = { - {'a', tr("Data reference graph (aga)")}, - {'A', tr("Global data references graph (agA)")}, + { 'a', tr("Data reference graph (aga)") }, + { 'A', tr("Global data references graph (agA)") }, // {'c', tr("c - Function callgraph")}, // {'C', tr("C - Global callgraph")}, // {'f', tr("f - Basic blocks function graph")}, - {'i', tr("Imports graph (agi)")}, - {'r', tr("References graph (agr)")}, - {'R', tr("Global references graph (agR)")}, - {'x', tr("Cross references graph (agx)")}, - {'g', tr("Custom graph (agg)")}, - {' ', tr("User command")}, + { 'i', tr("Imports graph (agi)") }, + { 'r', tr("References graph (agr)") }, + { 'R', tr("Global references graph (agR)") }, + { 'x', tr("Cross references graph (agx)") }, + { 'g', tr("Custom graph (agg)") }, + { ' ', tr("User command") }, }; for (auto &graphType : types) { if (graphType.commandChar != ' ') { @@ -37,13 +36,12 @@ RizinGraphWidget::RizinGraphWidget(MainWindow *main) } else { ui->graphType->addItem(graphType.label, QVariant()); } - } - connect(ui->graphType, &QComboBox::currentIndexChanged, this, &RizinGraphWidget::typeChanged); - connect(ui->customCommand, &QLineEdit::textEdited, this, [this](){ - graphView->setGraphCommand(ui->customCommand->text()); - }); - connect(ui->customCommand, &QLineEdit::returnPressed, this, [this](){ + connect(ui->graphType, &QComboBox::currentIndexChanged, this, + &RizinGraphWidget::typeChanged); + connect(ui->customCommand, &QLineEdit::textEdited, this, + [this]() { graphView->setGraphCommand(ui->customCommand->text()); }); + connect(ui->customCommand, &QLineEdit::returnPressed, this, [this]() { graphView->setGraphCommand(ui->customCommand->text()); graphView->refreshView(); }); @@ -51,9 +49,7 @@ RizinGraphWidget::RizinGraphWidget(MainWindow *main) typeChanged(); } -RizinGraphWidget::~RizinGraphWidget() -{ -} +RizinGraphWidget::~RizinGraphWidget() {} void RizinGraphWidget::typeChanged() { @@ -71,11 +67,11 @@ void RizinGraphWidget::typeChanged() } GenericRizinGraphView::GenericRizinGraphView(RizinGraphWidget *parent, MainWindow *main) - : SimpleTextGraphView(parent, main) - , refreshDeferrer(nullptr, this) + : SimpleTextGraphView(parent, main), refreshDeferrer(nullptr, this) { refreshDeferrer.registerFor(parent); - connect(&refreshDeferrer, &RefreshDeferrer::refreshNow, this, &GenericRizinGraphView::refreshView); + connect(&refreshDeferrer, &RefreshDeferrer::refreshNow, this, + &GenericRizinGraphView::refreshView); } void GenericRizinGraphView::setGraphCommand(QString cmd) diff --git a/src/widgets/RizinGraphWidget.h b/src/widgets/RizinGraphWidget.h index 20526e19..083c095d 100644 --- a/src/widgets/RizinGraphWidget.h +++ b/src/widgets/RizinGraphWidget.h @@ -41,15 +41,16 @@ public: GenericRizinGraphView(RizinGraphWidget *parent, MainWindow *main); void setGraphCommand(QString cmd); void refreshView() override; + protected: void loadCurrentGraph() override; + private: RefreshDeferrer refreshDeferrer; QString graphCommand; QString lastShownCommand; }; - class RizinGraphWidget : public CutterDockWidget { Q_OBJECT diff --git a/src/widgets/SdbWidget.cpp b/src/widgets/SdbWidget.cpp index 4b47bea8..98726e0e 100644 --- a/src/widgets/SdbWidget.cpp +++ b/src/widgets/SdbWidget.cpp @@ -7,16 +7,13 @@ #include #include - -SdbWidget::SdbWidget(MainWindow *main) : - CutterDockWidget(main), - ui(new Ui::SdbWidget) +SdbWidget::SdbWidget(MainWindow *main) : CutterDockWidget(main), ui(new Ui::SdbWidget) { ui->setupUi(this); path.clear(); - connect(Core(), &CutterCore::refreshAll, this, [this](){ reload(); }); + connect(Core(), &CutterCore::refreshAll, this, [this]() { reload(); }); reload(); } @@ -35,8 +32,8 @@ void SdbWidget::reload(QString _path) QTreeWidgetItem *tempItem = new QTreeWidgetItem(); tempItem->setText(0, key); tempItem->setText(1, Core()->sdbGet(path, key)); - tempItem->setFlags(Qt::ItemIsSelectable | Qt::ItemIsUserCheckable | Qt::ItemIsEnabled | - Qt::ItemIsDragEnabled | Qt::ItemIsEditable); + tempItem->setFlags(Qt::ItemIsSelectable | Qt::ItemIsUserCheckable | Qt::ItemIsEnabled + | Qt::ItemIsDragEnabled | Qt::ItemIsEditable); ui->treeWidget->insertTopLevelItem(0, tempItem); } qhelpers::adjustColumns(ui->treeWidget, 0); @@ -54,7 +51,6 @@ void SdbWidget::reload(QString _path) qhelpers::adjustColumns(ui->treeWidget, 0); } - void SdbWidget::on_treeWidget_itemDoubleClicked(QTreeWidgetItem *item, int column) { if (column < 0) diff --git a/src/widgets/SdbWidget.h b/src/widgets/SdbWidget.h index 2525725a..a420d326 100644 --- a/src/widgets/SdbWidget.h +++ b/src/widgets/SdbWidget.h @@ -30,7 +30,6 @@ private slots: private: std::unique_ptr ui; QString path; - }; #endif // SDBWIDGET_H diff --git a/src/widgets/SearchWidget.cpp b/src/widgets/SearchWidget.cpp index 97295293..dca8f970 100644 --- a/src/widgets/SearchWidget.cpp +++ b/src/widgets/SearchWidget.cpp @@ -17,25 +17,22 @@ static const int kMaxTooltipHexdumpBytes = 64; } static const QMap searchBoundaries { - {"io.maps", "All maps"}, - {"io.map", "Current map"}, - {"raw", "Raw"}, - {"block", "Current block"}, - {"bin.section", "Current mapped section"}, - {"bin.sections", "All mapped sections"}, + { "io.maps", "All maps" }, + { "io.map", "Current map" }, + { "raw", "Raw" }, + { "block", "Current block" }, + { "bin.section", "Current mapped section" }, + { "bin.sections", "All mapped sections" }, }; -static const QMap searchBoundariesDebug { - {"dbg.maps", "All memory maps"}, - {"dbg.map", "Memory map"}, - {"block", "Current block"}, - {"dbg.stack", "Stack"}, - {"dbg.heap", "Heap"} -}; +static const QMap searchBoundariesDebug { { "dbg.maps", "All memory maps" }, + { "dbg.map", "Memory map" }, + { "block", "Current block" }, + { "dbg.stack", "Stack" }, + { "dbg.heap", "Heap" } }; SearchModel::SearchModel(QList *search, QObject *parent) - : AddressableItemModel(parent), - search(search) + : AddressableItemModel(parent), search(search) { } @@ -77,22 +74,27 @@ QVariant SearchModel::data(const QModelIndex &index, int role) const QString previewContent = QString(); // if result is CODE, show disassembly if (!exp.code.isEmpty()) { - previewContent = Core()->getDisassemblyPreview(exp.offset, kMaxTooltipDisasmPreviewLines) - .join("
"); - // if result is DATA or Disassembly is N/A + previewContent = + Core()->getDisassemblyPreview(exp.offset, kMaxTooltipDisasmPreviewLines) + .join("
"); + // if result is DATA or Disassembly is N/A } else if (!exp.data.isEmpty() || previewContent.isEmpty()) { previewContent = Core()->getHexdumpPreview(exp.offset, kMaxTooltipHexdumpBytes); } const QFont &fnt = Config()->getBaseFont(); - QFontMetrics fm{ fnt }; + QFontMetrics fm { fnt }; - QString toolTipContent = QString("
") - .arg(fnt.family()) - .arg(qMax(6, fnt.pointSize() - 1)); // slightly decrease font size, to keep more text in the same box - - toolTipContent += tr("
Preview:
%1
") - .arg(previewContent); + QString toolTipContent = + QString("
") + .arg(fnt.family()) + .arg(qMax(6, fnt.pointSize() - 1)); // slightly decrease font size, to keep + // more text in the same box + + toolTipContent += + tr("
Preview:
%1
") + .arg(previewContent); toolTipContent += "
"; return toolTipContent; @@ -133,7 +135,6 @@ RVA SearchModel::address(const QModelIndex &index) const return exp.offset; } - SearchSortFilterProxyModel::SearchSortFilterProxyModel(SearchModel *source_model, QObject *parent) : AddressableFilterProxyModel(source_model, parent) { @@ -142,17 +143,17 @@ SearchSortFilterProxyModel::SearchSortFilterProxyModel(SearchModel *source_model bool SearchSortFilterProxyModel::filterAcceptsRow(int row, const QModelIndex &parent) const { QModelIndex index = sourceModel()->index(row, 0, parent); - SearchDescription search = index.data( - SearchModel::SearchDescriptionRole).value(); + SearchDescription search = + index.data(SearchModel::SearchDescriptionRole).value(); return search.code.contains(filterRegExp()); } bool SearchSortFilterProxyModel::lessThan(const QModelIndex &left, const QModelIndex &right) const { - SearchDescription left_search = left.data( - SearchModel::SearchDescriptionRole).value(); - SearchDescription right_search = right.data( - SearchModel::SearchDescriptionRole).value(); + SearchDescription left_search = + left.data(SearchModel::SearchDescriptionRole).value(); + SearchDescription right_search = + right.data(SearchModel::SearchDescriptionRole).value(); switch (left.column()) { case SearchModel::SIZE: @@ -172,10 +173,7 @@ bool SearchSortFilterProxyModel::lessThan(const QModelIndex &left, const QModelI return left_search.offset < right_search.offset; } - -SearchWidget::SearchWidget(MainWindow *main) : - CutterDockWidget(main), - ui(new Ui::SearchWidget) +SearchWidget::SearchWidget(MainWindow *main) : CutterDockWidget(main), ui(new Ui::SearchWidget) { ui->setupUi(this); setStyleSheet(QString("QToolTip { max-width: %1px; opacity: 230; }").arg(kMaxTooltipWidth)); @@ -192,9 +190,8 @@ SearchWidget::SearchWidget(MainWindow *main) : connect(Core(), &CutterCore::toggleDebugView, this, &SearchWidget::updateSearchBoundaries); connect(Core(), &CutterCore::refreshAll, this, &SearchWidget::refreshSearchspaces); - connect(Core(), &CutterCore::commentsChanged, this, [this]() { - qhelpers::emitColumnChanged(search_model, SearchModel::COMMENT); - }); + connect(Core(), &CutterCore::commentsChanged, this, + [this]() { qhelpers::emitColumnChanged(search_model, SearchModel::COMMENT); }); QShortcut *enter_press = new QShortcut(QKeySequence(Qt::Key_Return), this); connect(enter_press, &QShortcut::activated, this, [this]() { @@ -208,8 +205,9 @@ SearchWidget::SearchWidget(MainWindow *main) : checkSearchResultEmpty(); }); - connect(ui->searchspaceCombo, static_cast(&QComboBox::currentIndexChanged), - this, [this](int index) { updatePlaceholderText(index);}); + connect(ui->searchspaceCombo, + static_cast(&QComboBox::currentIndexChanged), this, + [this](int index) { updatePlaceholderText(index); }); } SearchWidget::~SearchWidget() {} @@ -250,8 +248,8 @@ void SearchWidget::refreshSearchspaces() cur_idx = 0; ui->searchspaceCombo->clear(); - ui->searchspaceCombo->addItem(tr("asm code"), QVariant("/acj")); - ui->searchspaceCombo->addItem(tr("string"), QVariant("/j")); + ui->searchspaceCombo->addItem(tr("asm code"), QVariant("/acj")); + ui->searchspaceCombo->addItem(tr("string"), QVariant("/j")); ui->searchspaceCombo->addItem(tr("hex string"), QVariant("/xj")); ui->searchspaceCombo->addItem(tr("ROP gadgets"), QVariant("/Rj")); ui->searchspaceCombo->addItem(tr("32bit value"), QVariant("/vj")); @@ -279,8 +277,8 @@ void SearchWidget::refreshSearch() // Called by &QShortcut::activated and &QAbstractButton::clicked signals void SearchWidget::checkSearchResultEmpty() { - if (search.isEmpty()){ - QString noResultsMessage=""; + if (search.isEmpty()) { + QString noResultsMessage = ""; noResultsMessage.append(tr("No results found for:")); noResultsMessage.append("
"); noResultsMessage.append(ui->filterLineEdit->text().toHtmlEscaped()); diff --git a/src/widgets/SearchWidget.h b/src/widgets/SearchWidget.h index ac836418..8da8b25b 100644 --- a/src/widgets/SearchWidget.h +++ b/src/widgets/SearchWidget.h @@ -14,8 +14,7 @@ class MainWindow; class QTreeWidgetItem; class SearchWidget; - -class SearchModel: public AddressableItemModel +class SearchModel : public AddressableItemModel { Q_OBJECT @@ -34,13 +33,12 @@ public: int columnCount(const QModelIndex &parent = QModelIndex()) const override; QVariant data(const QModelIndex &index, int role) const override; - QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; + QVariant headerData(int section, Qt::Orientation orientation, + int role = Qt::DisplayRole) const override; RVA address(const QModelIndex &index) const override; }; - - class SearchSortFilterProxyModel : public AddressableFilterProxyModel { Q_OBJECT @@ -53,8 +51,6 @@ protected: bool lessThan(const QModelIndex &left, const QModelIndex &right) const override; }; - - namespace Ui { class SearchWidget; } diff --git a/src/widgets/SectionsWidget.cpp b/src/widgets/SectionsWidget.cpp index 61b8e4f0..ef5a170d 100644 --- a/src/widgets/SectionsWidget.cpp +++ b/src/widgets/SectionsWidget.cpp @@ -14,8 +14,7 @@ #include SectionsModel::SectionsModel(QList *sections, QObject *parent) - : AddressableItemModel(parent), - sections(sections) + : AddressableItemModel(parent), sections(sections) { } @@ -32,18 +31,19 @@ int SectionsModel::columnCount(const QModelIndex &) const QVariant SectionsModel::data(const QModelIndex &index, int role) const { // TODO: create unique colors, e. g. use HSV color space and rotate in H for 360/size - static const QList colors = { QColor("#1ABC9C"), //TURQUOISE - QColor("#2ECC71"), //EMERALD - QColor("#3498DB"), //PETER RIVER - QColor("#9B59B6"), //AMETHYST - QColor("#34495E"), //WET ASPHALT - QColor("#F1C40F"), //SUN FLOWER - QColor("#E67E22"), //CARROT - QColor("#E74C3C"), //ALIZARIN - QColor("#ECF0F1"), //CLOUDS - QColor("#BDC3C7"), //SILVER - QColor("#95A5A6") //COBCRETE - }; + static const QList colors = { + QColor("#1ABC9C"), // TURQUOISE + QColor("#2ECC71"), // EMERALD + QColor("#3498DB"), // PETER RIVER + QColor("#9B59B6"), // AMETHYST + QColor("#34495E"), // WET ASPHALT + QColor("#F1C40F"), // SUN FLOWER + QColor("#E67E22"), // CARROT + QColor("#E74C3C"), // ALIZARIN + QColor("#ECF0F1"), // CLOUDS + QColor("#BDC3C7"), // SILVER + QColor("#95A5A6") // COBCRETE + }; if (index.row() >= sections->count()) { return QVariant(); @@ -135,7 +135,8 @@ SectionsProxyModel::SectionsProxyModel(SectionsModel *sourceModel, QObject *pare bool SectionsProxyModel::lessThan(const QModelIndex &left, const QModelIndex &right) const { auto leftSection = left.data(SectionsModel::SectionDescriptionRole).value(); - auto rightSection = right.data(SectionsModel::SectionDescriptionRole).value(); + auto rightSection = + right.data(SectionsModel::SectionDescriptionRole).value(); switch (left.column()) { default: @@ -160,8 +161,7 @@ bool SectionsProxyModel::lessThan(const QModelIndex &left, const QModelIndex &ri } } -SectionsWidget::SectionsWidget(MainWindow *main) : - ListDockWidget(main) +SectionsWidget::SectionsWidget(MainWindow *main) : ListDockWidget(main) { setObjectName("SectionsWidget"); setWindowTitle(QStringLiteral("Sections")); @@ -228,26 +228,25 @@ void SectionsWidget::initConnects() { connect(Core(), &CutterCore::refreshAll, this, &SectionsWidget::refreshSections); connect(Core(), &CutterCore::codeRebased, this, &SectionsWidget::refreshSections); - connect(this, &QDockWidget::visibilityChanged, this, [ = ](bool visibility) { + connect(this, &QDockWidget::visibilityChanged, this, [=](bool visibility) { if (visibility) { refreshSections(); } }); connect(Core(), &CutterCore::seekChanged, this, &SectionsWidget::refreshDocks); connect(Config(), &Configuration::colorsUpdated, this, &SectionsWidget::refreshSections); - connect(toggleButton, &QToolButton::clicked, this, [ = ] { + connect(toggleButton, &QToolButton::clicked, this, [=] { toggleButton->hide(); addrDockWidget->show(); virtualAddrDock->show(); }); - connect(virtualAddrDock, &QDockWidget::visibilityChanged, this, [ = ](bool visibility) { + connect(virtualAddrDock, &QDockWidget::visibilityChanged, this, [=](bool visibility) { if (!visibility) { updateToggle(); } }); - connect(Core(), &CutterCore::commentsChanged, this, [this]() { - qhelpers::emitColumnChanged(sectionsModel, SectionsModel::CommentColumn); - }); + connect(Core(), &CutterCore::commentsChanged, this, + [this]() { qhelpers::emitColumnChanged(sectionsModel, SectionsModel::CommentColumn); }); } void SectionsWidget::refreshSections() @@ -277,11 +276,15 @@ void SectionsWidget::drawIndicatorOnAddrDocks() RVA offset = Core()->getOffset(); for (int i = 0; i != virtualAddrDock->proxyModel->rowCount(); i++) { QModelIndex idx = virtualAddrDock->proxyModel->index(i, 0); - RVA vaddr = idx.data(SectionsModel::SectionDescriptionRole).value().vaddr; - int vsize = idx.data(SectionsModel::SectionDescriptionRole).value().vsize; + RVA vaddr = + idx.data(SectionsModel::SectionDescriptionRole).value().vaddr; + int vsize = + idx.data(SectionsModel::SectionDescriptionRole).value().vsize; RVA end = vaddr + vsize; if (offset < end) { - QString name = idx.data(SectionsModel::SectionDescriptionRole).value().name; + QString name = idx.data(SectionsModel::SectionDescriptionRole) + .value() + .name; float ratio = 0; if (vsize > 0 && offset > vaddr) { ratio = (float)(offset - vaddr) / (float)vsize; @@ -293,7 +296,8 @@ void SectionsWidget::drawIndicatorOnAddrDocks() } } -void SectionsWidget::resizeEvent(QResizeEvent *event) { +void SectionsWidget::resizeEvent(QResizeEvent *event) +{ CutterDockWidget::resizeEvent(event); refreshDocks(); } @@ -306,10 +310,10 @@ void SectionsWidget::updateToggle() } } -AbstractAddrDock::AbstractAddrDock(SectionsModel *model, QWidget *parent) : - QDockWidget(parent), - addrDockScene(new AddrDockScene(this)), - graphicsView(new QGraphicsView(this)) +AbstractAddrDock::AbstractAddrDock(SectionsModel *model, QWidget *parent) + : QDockWidget(parent), + addrDockScene(new AddrDockScene(this)), + graphicsView(new QGraphicsView(this)) { graphicsView->setScene(addrDockScene); setWidget(graphicsView); @@ -415,7 +419,8 @@ int AbstractAddrDock::getValidMinSize() proxyModel->sort(SectionsModel::SizeColumn, Qt::AscendingOrder); for (int i = 0; i < proxyModel->rowCount(); i++) { QModelIndex idx = proxyModel->index(i, 0); - int size = getSizeOfSection(idx.data(SectionsModel::SectionDescriptionRole).value()); + int size = getSizeOfSection( + idx.data(SectionsModel::SectionDescriptionRole).value()); if (size > 0) { return size; } @@ -429,7 +434,8 @@ void AbstractAddrDock::drawIndicator(QString name, float ratio) float padding = addrDockScene->nameHeightMap[name] * ratio; int y = addrDockScene->namePosYMap[name] + (int)padding; QColor color = indicatorColor; - QGraphicsRectItem *indicator = new QGraphicsRectItem(QRectF(0, y, getIndicatorWidth(), indicatorHeight)); + QGraphicsRectItem *indicator = + new QGraphicsRectItem(QRectF(0, y, getIndicatorWidth(), indicatorHeight)); indicator->setBrush(QBrush(color)); addrDockScene->addItem(indicator); @@ -441,8 +447,7 @@ void AbstractAddrDock::drawIndicator(QString name, float ratio) addTextItem(color, QPoint(0, y - indicatorParamPosY), QString("0x%1").arg(offset, 0, 16)); } -AddrDockScene::AddrDockScene(QWidget *parent) : - QGraphicsScene(parent) +AddrDockScene::AddrDockScene(QWidget *parent) : QGraphicsScene(parent) { disableCenterOn = false; } @@ -490,23 +495,19 @@ RVA AddrDockScene::getAddrFromPos(int posY, bool seek) return RVA_INVALID; } -RawAddrDock::RawAddrDock(SectionsModel *model, QWidget *parent) : - AbstractAddrDock(model, parent) +RawAddrDock::RawAddrDock(SectionsModel *model, QWidget *parent) : AbstractAddrDock(model, parent) { setWindowTitle(tr("Raw")); - connect(this, &QDockWidget::featuresChanged, this, [ = ](){ - setFeatures(QDockWidget::NoDockWidgetFeatures); - }); + connect(this, &QDockWidget::featuresChanged, this, + [=]() { setFeatures(QDockWidget::NoDockWidgetFeatures); }); } - -VirtualAddrDock::VirtualAddrDock(SectionsModel *model, QWidget *parent) : - AbstractAddrDock(model, parent) +VirtualAddrDock::VirtualAddrDock(SectionsModel *model, QWidget *parent) + : AbstractAddrDock(model, parent) { setWindowTitle(tr("Virtual")); - connect(this, &QDockWidget::featuresChanged, this, [ = ](){ - setFeatures(QDockWidget::DockWidgetClosable); - }); + connect(this, &QDockWidget::featuresChanged, this, + [=]() { setFeatures(QDockWidget::DockWidgetClosable); }); } void RawAddrDock::updateDock() diff --git a/src/widgets/SectionsWidget.h b/src/widgets/SectionsWidget.h index 1e5a89a0..9a7e9638 100644 --- a/src/widgets/SectionsWidget.h +++ b/src/widgets/SectionsWidget.h @@ -36,7 +36,17 @@ private: QList *sections; public: - enum Column { NameColumn = 0, SizeColumn, AddressColumn, EndAddressColumn, VirtualSizeColumn, PermissionsColumn, EntropyColumn, CommentColumn, ColumnCount }; + enum Column { + NameColumn = 0, + SizeColumn, + AddressColumn, + EndAddressColumn, + VirtualSizeColumn, + PermissionsColumn, + EntropyColumn, + CommentColumn, + ColumnCount + }; enum Role { SectionDescriptionRole = Qt::UserRole }; SectionsModel(QList *sections, QObject *parent = nullptr); @@ -73,6 +83,7 @@ public: private slots: void refreshSections(); void refreshDocks(); + protected: void resizeEvent(QResizeEvent *event) override; @@ -136,8 +147,8 @@ protected: int getIndicatorWidth(); int getValidMinSize(); - virtual RVA getSizeOfSection(const SectionDescription §ion) =0; - virtual RVA getAddressOfSection(const SectionDescription §ion) =0; + virtual RVA getSizeOfSection(const SectionDescription §ion) = 0; + virtual RVA getAddressOfSection(const SectionDescription §ion) = 0; private: void drawIndicator(QString name, float ratio); diff --git a/src/widgets/SegmentsWidget.cpp b/src/widgets/SegmentsWidget.cpp index 47ea167c..a2a35938 100644 --- a/src/widgets/SegmentsWidget.cpp +++ b/src/widgets/SegmentsWidget.cpp @@ -7,8 +7,7 @@ #include SegmentsModel::SegmentsModel(QList *segments, QObject *parent) - : AddressableItemModel(parent), - segments(segments) + : AddressableItemModel(parent), segments(segments) { } @@ -25,18 +24,19 @@ int SegmentsModel::columnCount(const QModelIndex &) const QVariant SegmentsModel::data(const QModelIndex &index, int role) const { // TODO: create unique colors, e. g. use HSV color space and rotate in H for 360/size - static const QList colors = { QColor("#1ABC9C"), //TURQUOISE - QColor("#2ECC71"), //EMERALD - QColor("#3498DB"), //PETER RIVER - QColor("#9B59B6"), //AMETHYST - QColor("#34495E"), //WET ASPHALT - QColor("#F1C40F"), //SUN FLOWER - QColor("#E67E22"), //CARROT - QColor("#E74C3C"), //ALIZARIN - QColor("#ECF0F1"), //CLOUDS - QColor("#BDC3C7"), //SILVER - QColor("#95A5A6") //COBCRETE - }; + static const QList colors = { + QColor("#1ABC9C"), // TURQUOISE + QColor("#2ECC71"), // EMERALD + QColor("#3498DB"), // PETER RIVER + QColor("#9B59B6"), // AMETHYST + QColor("#34495E"), // WET ASPHALT + QColor("#F1C40F"), // SUN FLOWER + QColor("#E67E22"), // CARROT + QColor("#E74C3C"), // ALIZARIN + QColor("#ECF0F1"), // CLOUDS + QColor("#BDC3C7"), // SILVER + QColor("#95A5A6") // COBCRETE + }; if (index.row() >= segments->count()) return QVariant(); @@ -119,7 +119,8 @@ SegmentsProxyModel::SegmentsProxyModel(SegmentsModel *sourceModel, QObject *pare bool SegmentsProxyModel::lessThan(const QModelIndex &left, const QModelIndex &right) const { auto leftSegment = left.data(SegmentsModel::SegmentDescriptionRole).value(); - auto rightSegment = right.data(SegmentsModel::SegmentDescriptionRole).value(); + auto rightSegment = + right.data(SegmentsModel::SegmentDescriptionRole).value(); switch (left.column()) { case SegmentsModel::NameColumn: return leftSegment.name < rightSegment.name; @@ -136,8 +137,7 @@ bool SegmentsProxyModel::lessThan(const QModelIndex &left, const QModelIndex &ri return false; } -SegmentsWidget::SegmentsWidget(MainWindow *main) : - ListDockWidget(main) +SegmentsWidget::SegmentsWidget(MainWindow *main) : ListDockWidget(main) { setObjectName("SegmentsWidget"); setWindowTitle(QStringLiteral("Segments")); @@ -153,9 +153,8 @@ SegmentsWidget::SegmentsWidget(MainWindow *main) : connect(Core(), &CutterCore::refreshAll, this, &SegmentsWidget::refreshSegments); connect(Core(), &CutterCore::codeRebased, this, &SegmentsWidget::refreshSegments); - connect(Core(), &CutterCore::commentsChanged, this, [this]() { - qhelpers::emitColumnChanged(segmentsModel, SegmentsModel::CommentColumn); - }); + connect(Core(), &CutterCore::commentsChanged, this, + [this]() { qhelpers::emitColumnChanged(segmentsModel, SegmentsModel::CommentColumn); }); } SegmentsWidget::~SegmentsWidget() {} diff --git a/src/widgets/SegmentsWidget.h b/src/widgets/SegmentsWidget.h index 260eef4f..47a07cf5 100644 --- a/src/widgets/SegmentsWidget.h +++ b/src/widgets/SegmentsWidget.h @@ -22,7 +22,15 @@ private: QList *segments; public: - enum Column { NameColumn = 0, SizeColumn, AddressColumn, EndAddressColumn, PermColumn, CommentColumn, ColumnCount }; + enum Column { + NameColumn = 0, + SizeColumn, + AddressColumn, + EndAddressColumn, + PermColumn, + CommentColumn, + ColumnCount + }; enum Role { SegmentDescriptionRole = Qt::UserRole }; SegmentsModel(QList *segments, QObject *parent = nullptr); @@ -31,7 +39,8 @@ public: int columnCount(const QModelIndex &parent = QModelIndex()) const override; QVariant data(const QModelIndex &index, int role) const override; - QVariant headerData(int segment, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; + QVariant headerData(int segment, Qt::Orientation orientation, + int role = Qt::DisplayRole) const override; RVA address(const QModelIndex &index) const override; QString name(const QModelIndex &index) const override; @@ -58,6 +67,7 @@ public: private slots: void refreshSegments(); + private: QList segments; SegmentsModel *segmentsModel; diff --git a/src/widgets/SimpleTextGraphView.cpp b/src/widgets/SimpleTextGraphView.cpp index 955e7e29..97fedac2 100644 --- a/src/widgets/SimpleTextGraphView.cpp +++ b/src/widgets/SimpleTextGraphView.cpp @@ -36,7 +36,8 @@ SimpleTextGraphView::SimpleTextGraphView(QWidget *parent, MainWindow *mainWindow contextMenu->addAction(&actionExportGraph); contextMenu->addMenu(layoutMenu); - addressableItemContextMenu.insertAction(addressableItemContextMenu.actions().first(), ©Action); + addressableItemContextMenu.insertAction(addressableItemContextMenu.actions().first(), + ©Action); addressableItemContextMenu.addSeparator(); addressableItemContextMenu.addAction(&actionExportGraph); addressableItemContextMenu.addMenu(layoutMenu); @@ -87,7 +88,7 @@ void SimpleTextGraphView::drawBlock(QPainter &p, GraphView::GraphBlock &block, b { QRectF blockRect(block.x, block.y, block.width, block.height); - const qreal padding = charWidth; + const qreal padding = charWidth; p.setPen(Qt::black); p.setBrush(Qt::gray); @@ -121,7 +122,7 @@ void SimpleTextGraphView::drawBlock(QPainter &p, GraphView::GraphBlock &block, b p.setPen(palette().color(QPalette::WindowText)); // Render node text auto x = block.x + padding; - int y = block.y + padding + p.fontMetrics().ascent(); + int y = block.y + padding + p.fontMetrics().ascent(); p.drawText(QPoint(x, y), content.text); } @@ -166,9 +167,9 @@ void SimpleTextGraphView::enableAddresses(bool enabled) haveAddresses = enabled; if (!enabled) { addressableItemContextMenu.clearTarget(); - // Clearing addreassable item context menu disables all the actions inside it including extra ones added - // by SimpleTextGraphView. Re-enable them because they are in the regular context menu as well and shouldn't be - // disabled. + // Clearing addreassable item context menu disables all the actions inside it including + // extra ones added by SimpleTextGraphView. Re-enable them because they are in the regular + // context menu as well and shouldn't be disabled. for (auto action : contextMenu->actions()) { action->setEnabled(true); } @@ -187,9 +188,8 @@ void SimpleTextGraphView::copyBlockText() void SimpleTextGraphView::contextMenuEvent(QContextMenuEvent *event) { GraphView::contextMenuEvent(event); - if (!event->isAccepted() && - event->reason() != QContextMenuEvent::Mouse && - enableBlockSelection && selectedBlock != NO_BLOCK_SELECTED) { + if (!event->isAccepted() && event->reason() != QContextMenuEvent::Mouse && enableBlockSelection + && selectedBlock != NO_BLOCK_SELECTED) { auto blockIt = blocks.find(selectedBlock); if (blockIt != blocks.end()) { blockContextMenuRequested(blockIt->second, event, {}); @@ -219,7 +219,6 @@ void SimpleTextGraphView::blockContextMenuRequested(GraphView::GraphBlock &block addressableItemContextMenu.exec(pos); event->accept(); } - } void SimpleTextGraphView::blockHelpEvent(GraphView::GraphBlock &block, QHelpEvent *event, @@ -234,7 +233,7 @@ void SimpleTextGraphView::blockClicked(GraphView::GraphBlock &block, QMouseEvent QPoint /*pos*/) { if ((event->button() == Qt::LeftButton || event->button() == Qt::RightButton) - && enableBlockSelection) { + && enableBlockSelection) { selectBlockWithId(block.entry); } } diff --git a/src/widgets/SimpleTextGraphView.h b/src/widgets/SimpleTextGraphView.h index cb13a9f4..cc1cf25f 100644 --- a/src/widgets/SimpleTextGraphView.h +++ b/src/widgets/SimpleTextGraphView.h @@ -39,12 +39,13 @@ public slots: * @brief Select a given block. Requires block selection to be enabled. */ void selectBlockWithId(ut64 blockId); + protected: void paintEvent(QPaintEvent *event) override; void contextMenuEvent(QContextMenuEvent *event) override; void blockContextMenuRequested(GraphView::GraphBlock &block, QContextMenuEvent *event, QPoint pos) override; - void blockHelpEvent(GraphView::GraphBlock &block, QHelpEvent *event, QPoint pos)override; + void blockHelpEvent(GraphView::GraphBlock &block, QHelpEvent *event, QPoint pos) override; void blockClicked(GraphView::GraphBlock &block, QMouseEvent *event, QPoint pos) override; void restoreCurrentBlock() override; @@ -63,7 +64,8 @@ protected: */ void enableAddresses(bool enabled); - struct BlockContent { + struct BlockContent + { QString text; RVA address; }; @@ -78,6 +80,7 @@ protected: ut64 selectedBlock = NO_BLOCK_SELECTED; bool enableBlockSelection = true; bool haveAddresses = false; + private: void copyBlockText(); }; diff --git a/src/widgets/StackWidget.cpp b/src/widgets/StackWidget.cpp index 721c07ef..88ed9a87 100644 --- a/src/widgets/StackWidget.cpp +++ b/src/widgets/StackWidget.cpp @@ -8,11 +8,11 @@ #include "QHeaderView" #include "QMenu" -StackWidget::StackWidget(MainWindow *main) : - CutterDockWidget(main), - ui(new Ui::StackWidget), - menuText(this), - addressableItemContextMenu(this, main) +StackWidget::StackWidget(MainWindow *main) + : CutterDockWidget(main), + ui(new Ui::StackWidget), + menuText(this), + addressableItemContextMenu(this, main) { ui->setupUi(this); @@ -26,28 +26,27 @@ StackWidget::StackWidget(MainWindow *main) : viewStack->setAutoScroll(false); viewStack->setHorizontalScrollMode(QAbstractItemView::ScrollPerPixel); ui->verticalLayout->addWidget(viewStack); - viewStack->setEditTriggers(viewStack->editTriggers() & - ~(QAbstractItemView::DoubleClicked | QAbstractItemView::AnyKeyPressed)); + viewStack->setEditTriggers( + viewStack->editTriggers() + & ~(QAbstractItemView::DoubleClicked | QAbstractItemView::AnyKeyPressed)); editAction = new QAction(tr("Edit stack value..."), this); viewStack->setContextMenuPolicy(Qt::CustomContextMenu); - refreshDeferrer = createRefreshDeferrer([this]() { - updateContents(); - }); + refreshDeferrer = createRefreshDeferrer([this]() { updateContents(); }); connect(Core(), &CutterCore::refreshAll, this, &StackWidget::updateContents); connect(Core(), &CutterCore::registersChanged, this, &StackWidget::updateContents); connect(Core(), &CutterCore::stackChanged, this, &StackWidget::updateContents); - connect(Core(), &CutterCore::commentsChanged, this, [this]() { - qhelpers::emitColumnChanged(modelStack, StackModel::CommentColumn); - }); + connect(Core(), &CutterCore::commentsChanged, this, + [this]() { qhelpers::emitColumnChanged(modelStack, StackModel::CommentColumn); }); connect(Config(), &Configuration::fontsUpdated, this, &StackWidget::fontsUpdatedSlot); connect(viewStack, &QAbstractItemView::doubleClicked, this, &StackWidget::onDoubleClicked); - connect(viewStack, &QWidget::customContextMenuRequested, this, &StackWidget::customMenuRequested); + connect(viewStack, &QWidget::customContextMenuRequested, this, + &StackWidget::customMenuRequested); connect(editAction, &QAction::triggered, this, &StackWidget::editStack); - connect(viewStack->selectionModel(), &QItemSelectionModel::currentChanged, - this, &StackWidget::onCurrentChanged); + connect(viewStack->selectionModel(), &QItemSelectionModel::currentChanged, this, + &StackWidget::onCurrentChanged); addressableItemContextMenu.addAction(editAction); addActions(addressableItemContextMenu.actions()); @@ -129,7 +128,8 @@ void StackWidget::onCurrentChanged(const QModelIndex ¤t, const QModelIndex if (currentIndex.column() != StackModel::DescriptionColumn) { offsetString = currentIndex.data().toString(); } else { - offsetString = currentIndex.sibling(currentIndex.row(), StackModel::ValueColumn).data().toString(); + offsetString = + currentIndex.sibling(currentIndex.row(), StackModel::ValueColumn).data().toString(); } RVA offset = Core()->math(offsetString); @@ -141,10 +141,7 @@ void StackWidget::onCurrentChanged(const QModelIndex ¤t, const QModelIndex } } -StackModel::StackModel(QObject *parent) - : QAbstractTableModel(parent) -{ -} +StackModel::StackModel(QObject *parent) : QAbstractTableModel(parent) {} void StackModel::reload() { diff --git a/src/widgets/StackWidget.h b/src/widgets/StackWidget.h index 5cc6cef0..9feb801b 100644 --- a/src/widgets/StackWidget.h +++ b/src/widgets/StackWidget.h @@ -19,13 +19,14 @@ class StackModel : public QAbstractTableModel { Q_OBJECT public: - struct Item { + struct Item + { RVA offset; QString value; RefDescription refDesc; }; - enum Column { OffsetColumn = 0, ValueColumn, DescriptionColumn, CommentColumn, ColumnCount}; + enum Column { OffsetColumn = 0, ValueColumn, DescriptionColumn, CommentColumn, ColumnCount }; enum Role { StackDescriptionRole = Qt::UserRole }; StackModel(QObject *parent = nullptr); @@ -36,14 +37,14 @@ public: int columnCount(const QModelIndex &parent = QModelIndex()) const override; QVariant data(const QModelIndex &index, int role) const override; - QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; + QVariant headerData(int section, Qt::Orientation orientation, + int role = Qt::DisplayRole) const override; bool setData(const QModelIndex &index, const QVariant &value, int role) override; Qt::ItemFlags flags(const QModelIndex &index) const override; private: QVector values; - }; Q_DECLARE_METATYPE(StackModel::Item) @@ -63,6 +64,7 @@ private slots: void customMenuRequested(QPoint pos); void editStack(); void onCurrentChanged(const QModelIndex ¤t, const QModelIndex &previous); + private: std::unique_ptr ui; QTableView *viewStack = new QTableView(this); @@ -71,5 +73,4 @@ private: QAction menuText; RefreshDeferrer *refreshDeferrer; AddressableItemContextMenu addressableItemContextMenu; - }; diff --git a/src/widgets/StringsWidget.cpp b/src/widgets/StringsWidget.cpp index eb2aebbd..7c3dec30 100644 --- a/src/widgets/StringsWidget.cpp +++ b/src/widgets/StringsWidget.cpp @@ -10,8 +10,7 @@ #include StringsModel::StringsModel(QList *strings, QObject *parent) - : AddressableItemModel(parent), - strings(strings) + : AddressableItemModel(parent), strings(strings) { } @@ -107,7 +106,8 @@ StringsProxyModel::StringsProxyModel(StringsModel *sourceModel, QObject *parent) bool StringsProxyModel::filterAcceptsRow(int row, const QModelIndex &parent) const { QModelIndex index = sourceModel()->index(row, 0, parent); - StringDescription str = index.data(StringsModel::StringDescriptionRole).value(); + StringDescription str = + index.data(StringsModel::StringDescriptionRole).value(); if (selectedSection.isEmpty()) return str.string.contains(filterRegExp()); else @@ -143,10 +143,8 @@ bool StringsProxyModel::lessThan(const QModelIndex &left, const QModelIndex &rig return leftStr->vaddr < rightStr->vaddr; } -StringsWidget::StringsWidget(MainWindow *main) : - CutterDockWidget(main), - ui(new Ui::StringsWidget), - tree(new CutterTreeWidget(this)) +StringsWidget::StringsWidget(MainWindow *main) + : CutterDockWidget(main), ui(new Ui::StringsWidget), tree(new CutterTreeWidget(this)) { ui->setupUi(this); ui->quickFilterView->setLabelText(tr("Section:")); @@ -158,9 +156,7 @@ StringsWidget::StringsWidget(MainWindow *main) : // Shift-F12 to toggle strings window QShortcut *toggle_shortcut = new QShortcut(widgetShortcuts["StringsWidget"], main); - connect(toggle_shortcut, &QShortcut::activated, this, [ = ] () { - toggleDockWidget(true); - }); + connect(toggle_shortcut, &QShortcut::activated, this, [=]() { toggleDockWidget(true); }); connect(ui->actionCopy_String, &QAction::triggered, this, &StringsWidget::on_actionCopy); @@ -178,12 +174,11 @@ StringsWidget::StringsWidget(MainWindow *main) : auto menu = ui->stringsTreeView->getItemContextMenu(); menu->addAction(ui->actionCopy_String); - connect(ui->quickFilterView, &ComboQuickFilterView::filterTextChanged, - proxyModel, &QSortFilterProxyModel::setFilterWildcard); + connect(ui->quickFilterView, &ComboQuickFilterView::filterTextChanged, proxyModel, + &QSortFilterProxyModel::setFilterWildcard); - connect(ui->quickFilterView, &ComboQuickFilterView::filterTextChanged, this, [this] { - tree->showItemsNumber(proxyModel->rowCount()); - }); + connect(ui->quickFilterView, &ComboQuickFilterView::filterTextChanged, this, + [this] { tree->showItemsNumber(proxyModel->rowCount()); }); QShortcut *searchShortcut = new QShortcut(QKeySequence::Find, this); connect(searchShortcut, &QShortcut::activated, ui->quickFilterView, @@ -199,18 +194,14 @@ StringsWidget::StringsWidget(MainWindow *main) : connect(Core(), &CutterCore::refreshAll, this, &StringsWidget::refreshStrings); connect(Core(), &CutterCore::codeRebased, this, &StringsWidget::refreshStrings); - connect(Core(), &CutterCore::commentsChanged, this, [this]() { - qhelpers::emitColumnChanged(model, StringsModel::CommentColumn); - }); + connect(Core(), &CutterCore::commentsChanged, this, + [this]() { qhelpers::emitColumnChanged(model, StringsModel::CommentColumn); }); - connect( - ui->quickFilterView->comboBox(), &QComboBox::currentTextChanged, this, - [this]() { - proxyModel->selectedSection = ui->quickFilterView->comboBox()->currentData().toString(); - proxyModel->setFilterRegExp(proxyModel->filterRegExp()); - tree->showItemsNumber(proxyModel->rowCount()); - } - ); + connect(ui->quickFilterView->comboBox(), &QComboBox::currentTextChanged, this, [this]() { + proxyModel->selectedSection = ui->quickFilterView->comboBox()->currentData().toString(); + proxyModel->setFilterRegExp(proxyModel->filterRegExp()); + tree->showItemsNumber(proxyModel->rowCount()); + }); auto header = ui->stringsTreeView->header(); header->setSectionResizeMode(QHeaderView::ResizeMode::ResizeToContents); diff --git a/src/widgets/StringsWidget.h b/src/widgets/StringsWidget.h index ec6788b5..15a5ce0f 100644 --- a/src/widgets/StringsWidget.h +++ b/src/widgets/StringsWidget.h @@ -20,7 +20,7 @@ namespace Ui { class StringsWidget; } -class StringsModel: public AddressableItemModel +class StringsModel : public AddressableItemModel { Q_OBJECT @@ -30,7 +30,16 @@ private: QList *strings; public: - enum Column { OffsetColumn = 0, StringColumn, TypeColumn, LengthColumn, SizeColumn, SectionColumn, CommentColumn, ColumnCount }; + enum Column { + OffsetColumn = 0, + StringColumn, + TypeColumn, + LengthColumn, + SizeColumn, + SectionColumn, + CommentColumn, + ColumnCount + }; static const int StringDescriptionRole = Qt::UserRole; StringsModel(QList *strings, QObject *parent = nullptr); @@ -46,8 +55,6 @@ public: const StringDescription *description(const QModelIndex &index) const; }; - - class StringsProxyModel : public AddressableFilterProxyModel { Q_OBJECT @@ -64,7 +71,6 @@ protected: QString selectedSection; }; - class StringsWidget : public CutterDockWidget { Q_OBJECT @@ -88,8 +94,7 @@ private: StringsModel *model; StringsProxyModel *proxyModel; QList strings; - CutterTreeWidget* tree; - + CutterTreeWidget *tree; }; #endif // STRINGSWIDGET_H diff --git a/src/widgets/SymbolsWidget.cpp b/src/widgets/SymbolsWidget.cpp index 82a89bb3..ff9625ec 100644 --- a/src/widgets/SymbolsWidget.cpp +++ b/src/widgets/SymbolsWidget.cpp @@ -6,8 +6,7 @@ #include SymbolsModel::SymbolsModel(QList *symbols, QObject *parent) - : AddressableItemModel(parent), - symbols(symbols) + : AddressableItemModel(parent), symbols(symbols) { } @@ -119,8 +118,7 @@ bool SymbolsProxyModel::lessThan(const QModelIndex &left, const QModelIndex &rig return false; } -SymbolsWidget::SymbolsWidget(MainWindow *main) : - ListDockWidget(main) +SymbolsWidget::SymbolsWidget(MainWindow *main) : ListDockWidget(main) { setWindowTitle(tr("Symbols")); setObjectName("SymbolsWidget"); @@ -132,9 +130,8 @@ SymbolsWidget::SymbolsWidget(MainWindow *main) : connect(Core(), &CutterCore::codeRebased, this, &SymbolsWidget::refreshSymbols); connect(Core(), &CutterCore::refreshAll, this, &SymbolsWidget::refreshSymbols); - connect(Core(), &CutterCore::commentsChanged, this, [this]() { - qhelpers::emitColumnChanged(symbolsModel, SymbolsModel::CommentColumn); - }); + connect(Core(), &CutterCore::commentsChanged, this, + [this]() { qhelpers::emitColumnChanged(symbolsModel, SymbolsModel::CommentColumn); }); } SymbolsWidget::~SymbolsWidget() {} diff --git a/src/widgets/SymbolsWidget.h b/src/widgets/SymbolsWidget.h index 2de7d5e3..a5618a59 100644 --- a/src/widgets/SymbolsWidget.h +++ b/src/widgets/SymbolsWidget.h @@ -9,13 +9,11 @@ #include "CutterDockWidget.h" #include "widgets/ListDockWidget.h" - class MainWindow; class QTreeWidgetItem; class SymbolsWidget; - -class SymbolsModel: public AddressableItemModel +class SymbolsModel : public AddressableItemModel { Q_OBJECT @@ -34,7 +32,8 @@ public: int columnCount(const QModelIndex &parent = QModelIndex()) const override; QVariant data(const QModelIndex &index, int role) const override; - QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; + QVariant headerData(int section, Qt::Orientation orientation, + int role = Qt::DisplayRole) const override; RVA address(const QModelIndex &index) const override; QString name(const QModelIndex &index) const override; @@ -52,7 +51,6 @@ protected: bool lessThan(const QModelIndex &left, const QModelIndex &right) const override; }; - class SymbolsWidget : public ListDockWidget { Q_OBJECT @@ -68,7 +66,6 @@ private: QList symbols; SymbolsModel *symbolsModel; SymbolsProxyModel *symbolsProxyModel; - }; #endif // SYMBOLSWIDGET_H diff --git a/src/widgets/ThreadsWidget.cpp b/src/widgets/ThreadsWidget.cpp index 3f3abb6a..ddb9f8f0 100644 --- a/src/widgets/ThreadsWidget.cpp +++ b/src/widgets/ThreadsWidget.cpp @@ -15,9 +15,7 @@ enum ColumnIndex { COLUMN_PATH, }; -ThreadsWidget::ThreadsWidget(MainWindow *main) : - CutterDockWidget(main), - ui(new Ui::ThreadsWidget) +ThreadsWidget::ThreadsWidget(MainWindow *main) : CutterDockWidget(main), ui(new Ui::ThreadsWidget) { ui->setupUi(this); @@ -36,7 +34,8 @@ ThreadsWidget::ThreadsWidget(MainWindow *main) : // CTRL+F switches to the filter view and opens it in case it's hidden QShortcut *searchShortcut = new QShortcut(QKeySequence::Find, this); - connect(searchShortcut, &QShortcut::activated, ui->quickFilterView, &QuickFilterView::showFilter); + connect(searchShortcut, &QShortcut::activated, ui->quickFilterView, + &QuickFilterView::showFilter); searchShortcut->setContext(Qt::WidgetWithChildrenShortcut); // ESC switches back to the thread table and clears the buffer @@ -47,9 +46,7 @@ ThreadsWidget::ThreadsWidget(MainWindow *main) : }); clearShortcut->setContext(Qt::WidgetWithChildrenShortcut); - refreshDeferrer = createRefreshDeferrer([this]() { - updateContents(); - }); + refreshDeferrer = createRefreshDeferrer([this]() { updateContents(); }); connect(ui->quickFilterView, &QuickFilterView::filterTextChanged, modelFilter, &ThreadsFilterModel::setFilterWildcard); @@ -110,7 +107,7 @@ void ThreadsWidget::setThreadsGrid() QJsonArray threadsValues = Core()->getProcessThreads(DEBUGGED_PID).array(); int i = 0; QFont font; - + for (const QJsonValue &value : threadsValues) { QJsonObject threadsItem = value.toObject(); int pid = threadsItem["pid"].toVariant().toInt(); @@ -137,7 +134,8 @@ void ThreadsWidget::setThreadsGrid() } modelFilter->setSourceModel(modelThreads); - ui->viewThreads->resizeColumnsToContents();; + ui->viewThreads->resizeColumnsToContents(); + ; } void ThreadsWidget::fontsUpdatedSlot() @@ -165,8 +163,7 @@ void ThreadsWidget::onActivated(const QModelIndex &index) updateContents(); } -ThreadsFilterModel::ThreadsFilterModel(QObject *parent) - : QSortFilterProxyModel(parent) +ThreadsFilterModel::ThreadsFilterModel(QObject *parent) : QSortFilterProxyModel(parent) { setFilterCaseSensitivity(Qt::CaseInsensitive); setSortCaseSensitivity(Qt::CaseInsensitive); diff --git a/src/widgets/TypesWidget.cpp b/src/widgets/TypesWidget.cpp index 228c0af4..925252d6 100644 --- a/src/widgets/TypesWidget.cpp +++ b/src/widgets/TypesWidget.cpp @@ -11,8 +11,7 @@ #include TypesModel::TypesModel(QList *types, QObject *parent) - : QAbstractListModel(parent), - types(types) + : QAbstractListModel(parent), types(types) { } @@ -86,7 +85,6 @@ bool TypesModel::removeRows(int row, int count, const QModelIndex &parent) return true; } - TypesSortFilterProxyModel::TypesSortFilterProxyModel(TypesModel *source_model, QObject *parent) : QSortFilterProxyModel(parent) { @@ -107,7 +105,8 @@ bool TypesSortFilterProxyModel::filterAcceptsRow(int row, const QModelIndex &par bool TypesSortFilterProxyModel::lessThan(const QModelIndex &left, const QModelIndex &right) const { TypeDescription left_exp = left.data(TypesModel::TypeDescriptionRole).value(); - TypeDescription right_exp = right.data(TypesModel::TypeDescriptionRole).value(); + TypeDescription right_exp = + right.data(TypesModel::TypeDescriptionRole).value(); switch (left.column()) { case TypesModel::TYPE: @@ -125,12 +124,8 @@ bool TypesSortFilterProxyModel::lessThan(const QModelIndex &left, const QModelIn return left_exp.size < right_exp.size; } - - -TypesWidget::TypesWidget(MainWindow *main) : - CutterDockWidget(main), - ui(new Ui::TypesWidget), - tree(new CutterTreeWidget(this)) +TypesWidget::TypesWidget(MainWindow *main) + : CutterDockWidget(main), ui(new Ui::TypesWidget), tree(new CutterTreeWidget(this)) { ui->setupUi(this); ui->quickFilterView->setLabelText(tr("Category")); @@ -150,44 +145,43 @@ TypesWidget::TypesWidget(MainWindow *main) : setScrollMode(); // Setup custom context menu - connect(ui->typesTreeView, &QWidget::customContextMenuRequested, - this, &TypesWidget::showTypesContextMenu); + connect(ui->typesTreeView, &QWidget::customContextMenuRequested, this, + &TypesWidget::showTypesContextMenu); ui->typesTreeView->setContextMenuPolicy(Qt::CustomContextMenu); - connect(ui->quickFilterView, &ComboQuickFilterView::filterTextChanged, types_proxy_model, &QSortFilterProxyModel::setFilterWildcard); - connect(ui->quickFilterView, &ComboQuickFilterView::filterTextChanged, this, [this] { - tree->showItemsNumber(types_proxy_model->rowCount()); - }); + connect(ui->quickFilterView, &ComboQuickFilterView::filterTextChanged, this, + [this] { tree->showItemsNumber(types_proxy_model->rowCount()); }); QShortcut *searchShortcut = new QShortcut(QKeySequence::Find, this); - connect(searchShortcut, &QShortcut::activated, ui->quickFilterView, &ComboQuickFilterView::showFilter); + connect(searchShortcut, &QShortcut::activated, ui->quickFilterView, + &ComboQuickFilterView::showFilter); searchShortcut->setContext(Qt::WidgetWithChildrenShortcut); QShortcut *clearShortcut = new QShortcut(QKeySequence(Qt::Key_Escape), this); - connect(clearShortcut, &QShortcut::activated, ui->quickFilterView, &ComboQuickFilterView::clearFilter); + connect(clearShortcut, &QShortcut::activated, ui->quickFilterView, + &ComboQuickFilterView::clearFilter); clearShortcut->setContext(Qt::WidgetWithChildrenShortcut); connect(Core(), &CutterCore::refreshAll, this, &TypesWidget::refreshTypes); - connect( - ui->quickFilterView->comboBox(), &QComboBox::currentTextChanged, this, - [this]() { - types_proxy_model->selectedCategory = ui->quickFilterView->comboBox()->currentData().toString(); - types_proxy_model->setFilterRegExp(types_proxy_model->filterRegExp()); - tree->showItemsNumber(types_proxy_model->rowCount()); - } - ); + connect(ui->quickFilterView->comboBox(), &QComboBox::currentTextChanged, this, [this]() { + types_proxy_model->selectedCategory = + ui->quickFilterView->comboBox()->currentData().toString(); + types_proxy_model->setFilterRegExp(types_proxy_model->filterRegExp()); + tree->showItemsNumber(types_proxy_model->rowCount()); + }); actionViewType = new QAction(tr("View Type"), this); actionEditType = new QAction(tr("Edit Type"), this); - connect (actionViewType, &QAction::triggered, [this]() { viewType(true) ;}); - connect (actionEditType, &QAction::triggered, [this]() { viewType(false) ;}); - connect (ui->typesTreeView, &QTreeView::doubleClicked, this, &TypesWidget::typeItemDoubleClicked); + connect(actionViewType, &QAction::triggered, [this]() { viewType(true); }); + connect(actionEditType, &QAction::triggered, [this]() { viewType(false); }); + connect(ui->typesTreeView, &QTreeView::doubleClicked, this, + &TypesWidget::typeItemDoubleClicked); } TypesWidget::~TypesWidget() {} @@ -199,7 +193,7 @@ void TypesWidget::refreshTypes() types_model->endResetModel(); QStringList categories; - for (TypeDescription exp: types) { + for (TypeDescription exp : types) { categories << exp.category; } categories.removeDuplicates(); @@ -261,7 +255,8 @@ void TypesWidget::showTypesContextMenu(const QPoint &pt) void TypesWidget::on_actionExport_Types_triggered() { - QString filename = QFileDialog::getSaveFileName(this, tr("Save File"), Config()->getRecentFolder()); + QString filename = + QFileDialog::getSaveFileName(this, tr("Save File"), Config()->getRecentFolder()); if (filename.isEmpty()) { return; } @@ -298,7 +293,7 @@ void TypesWidget::viewType(bool readOnly) TypeDescription t = index.data(TypesModel::TypeDescriptionRole).value(); if (!readOnly) { dialog.setWindowTitle(tr("Edit Type: ") + t.type); - connect(&dialog, &TypesInteractionDialog::newTypesLoaded, this, &TypesWidget::refreshTypes); + connect(&dialog, &TypesInteractionDialog::newTypesLoaded, this, &TypesWidget::refreshTypes); } else { dialog.setWindowTitle(tr("View Type: ") + t.type + tr(" (Read Only)")); } @@ -306,7 +301,6 @@ void TypesWidget::viewType(bool readOnly) dialog.exec(); } - void TypesWidget::on_actionDelete_Type_triggered() { QModelIndex proxyIndex = ui->typesTreeView->currentIndex(); @@ -319,7 +313,8 @@ void TypesWidget::on_actionDelete_Type_triggered() } TypeDescription exp = index.data(TypesModel::TypeDescriptionRole).value(); - QMessageBox::StandardButton reply = QMessageBox::question(this, tr("Cutter"), tr("Are you sure you want to delete \"%1\"?").arg(exp.type)); + QMessageBox::StandardButton reply = QMessageBox::question( + this, tr("Cutter"), tr("Are you sure you want to delete \"%1\"?").arg(exp.type)); if (reply == QMessageBox::Yes) { types_model->removeRow(index.row()); } @@ -338,7 +333,8 @@ void TypesWidget::on_actionLink_Type_To_Address_triggered() } } -void TypesWidget::typeItemDoubleClicked(const QModelIndex &index) { +void TypesWidget::typeItemDoubleClicked(const QModelIndex &index) +{ if (!index.isValid()) { return; } diff --git a/src/widgets/TypesWidget.h b/src/widgets/TypesWidget.h index 59c3f974..9372dd27 100644 --- a/src/widgets/TypesWidget.h +++ b/src/widgets/TypesWidget.h @@ -18,12 +18,10 @@ namespace Ui { class TypesWidget; } - class MainWindow; class QTreeWidgetItem; - -class TypesModel: public QAbstractListModel +class TypesModel : public QAbstractListModel { Q_OBJECT @@ -42,13 +40,12 @@ public: int columnCount(const QModelIndex &parent = QModelIndex()) const override; QVariant data(const QModelIndex &index, int role) const override; - QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; + QVariant headerData(int section, Qt::Orientation orientation, + int role = Qt::DisplayRole) const override; bool removeRows(int row, int count, const QModelIndex &parent = QModelIndex()) override; }; - - class TypesSortFilterProxyModel : public QSortFilterProxyModel { Q_OBJECT @@ -65,8 +62,6 @@ protected: QString selectedCategory; }; - - class TypesWidget : public CutterDockWidget { Q_OBJECT @@ -100,11 +95,10 @@ private slots: /** * @brief Executed on clicking either the Edit Type or View Type options in the context menu - * It will open the TypesInteractionDialog filled with the selected type. Depends on Edit or View mode - * the text view would be read-only or not. + * It will open the TypesInteractionDialog filled with the selected type. Depends on Edit or + * View mode the text view would be read-only or not. */ - void viewType(bool readOnly=true); - + void viewType(bool readOnly = true); /** * @brief Executed on clicking the Delete Type option in the context menu @@ -143,5 +137,4 @@ private: void refreshCategoryCombo(const QStringList &categories); }; - #endif // TYPESWIDGET_H diff --git a/src/widgets/VTablesWidget.cpp b/src/widgets/VTablesWidget.cpp index 9b982bb7..df3946d4 100644 --- a/src/widgets/VTablesWidget.cpp +++ b/src/widgets/VTablesWidget.cpp @@ -8,26 +8,27 @@ #include "ui_VTablesWidget.h" VTableModel::VTableModel(QList *vtables, QObject *parent) - : QAbstractItemModel(parent), - vtables(vtables) + : QAbstractItemModel(parent), vtables(vtables) { } QModelIndex VTableModel::index(int row, int column, const QModelIndex &parent) const { - return createIndex(row, column, (quintptr) parent.isValid() ? parent.row() : -1); + return createIndex(row, column, (quintptr)parent.isValid() ? parent.row() : -1); } QModelIndex VTableModel::parent(const QModelIndex &index) const { - return index.isValid() && index.internalId() != (quintptr) - 1 ? - this->index(index.internalId(), index.column()) : QModelIndex(); + return index.isValid() && index.internalId() != (quintptr)-1 + ? this->index(index.internalId(), index.column()) + : QModelIndex(); } int VTableModel::rowCount(const QModelIndex &parent) const { - return parent.isValid() ? (parent.parent().isValid() ? 0 : vtables->at( - parent.row()).methods.count()) : vtables->count(); + return parent.isValid() + ? (parent.parent().isValid() ? 0 : vtables->at(parent.row()).methods.count()) + : vtables->count(); } int VTableModel::columnCount(const QModelIndex &) const @@ -93,7 +94,6 @@ QVariant VTableModel::headerData(int section, Qt::Orientation, int role) const return QVariant(); } - VTableSortFilterProxyModel::VTableSortFilterProxyModel(VTableModel *model, QObject *parent) : QSortFilterProxyModel(parent) { @@ -116,7 +116,7 @@ bool VTableSortFilterProxyModel::filterAcceptsRow(int source_row, #if QT_VERSION < QT_VERSION_CHECK(5, 10, 0) else { QAbstractItemModel *const model = sourceModel(); - const QModelIndex source = model->index(source_row, 0, QModelIndex()); + const QModelIndex source = model->index(source_row, 0, QModelIndex()); const int rows = model->rowCount(source); for (int i = 0; i < rows; ++i) if (QSortFilterProxyModel::filterAcceptsRow(i, source)) @@ -126,11 +126,8 @@ bool VTableSortFilterProxyModel::filterAcceptsRow(int source_row, return false; } - -VTablesWidget::VTablesWidget(MainWindow *main) : - CutterDockWidget(main), - ui(new Ui::VTablesWidget), - tree(new CutterTreeWidget(this)) +VTablesWidget::VTablesWidget(MainWindow *main) + : CutterDockWidget(main), ui(new Ui::VTablesWidget), tree(new CutterTreeWidget(this)) { ui->setupUi(this); @@ -145,21 +142,23 @@ VTablesWidget::VTablesWidget(MainWindow *main) : // Esc to clear the filter entry QShortcut *clear_shortcut = new QShortcut(QKeySequence(Qt::Key_Escape), this); - connect(clear_shortcut, &QShortcut::activated, ui->quickFilterView, &QuickFilterView::clearFilter); + connect(clear_shortcut, &QShortcut::activated, ui->quickFilterView, + &QuickFilterView::clearFilter); clear_shortcut->setContext(Qt::WidgetWithChildrenShortcut); // Ctrl-F to show/hide the filter entry QShortcut *search_shortcut = new QShortcut(QKeySequence::Find, this); - connect(search_shortcut, &QShortcut::activated, ui->quickFilterView, &QuickFilterView::showFilter); + connect(search_shortcut, &QShortcut::activated, ui->quickFilterView, + &QuickFilterView::showFilter); search_shortcut->setContext(Qt::WidgetWithChildrenShortcut); connect(ui->quickFilterView, &QuickFilterView::filterTextChanged, proxy, &QSortFilterProxyModel::setFilterWildcard); - connect(ui->quickFilterView, &QuickFilterView::filterClosed, ui->vTableTreeView, [this](){ ui->vTableTreeView->setFocus(); }); + connect(ui->quickFilterView, &QuickFilterView::filterClosed, ui->vTableTreeView, + [this]() { ui->vTableTreeView->setFocus(); }); - connect(ui->quickFilterView, &QuickFilterView::filterTextChanged, this, [this] { - tree->showItemsNumber(proxy->rowCount()); - }); + connect(ui->quickFilterView, &QuickFilterView::filterTextChanged, this, + [this] { tree->showItemsNumber(proxy->rowCount()); }); connect(Core(), &CutterCore::codeRebased, this, &VTablesWidget::refreshVTables); connect(Core(), &CutterCore::refreshAll, this, &VTablesWidget::refreshVTables); @@ -167,9 +166,7 @@ VTablesWidget::VTablesWidget(MainWindow *main) : refreshDeferrer = createRefreshDeferrer([this]() { refreshVTables(); }); } -VTablesWidget::~VTablesWidget() -{ -} +VTablesWidget::~VTablesWidget() {} void VTablesWidget::refreshVTables() { @@ -196,10 +193,11 @@ void VTablesWidget::on_vTableTreeView_doubleClicked(const QModelIndex &index) QModelIndex parent = index.parent(); if (parent.isValid()) { - Core()->seekAndShow(index.data( - VTableModel::VTableDescriptionRole).value().addr); + Core()->seekAndShow(index.data(VTableModel::VTableDescriptionRole) + .value() + .addr); } else { - Core()->seekAndShow(index.data( - VTableModel::VTableDescriptionRole).value().addr); + Core()->seekAndShow( + index.data(VTableModel::VTableDescriptionRole).value().addr); } } diff --git a/src/widgets/VisualNavbar.cpp b/src/widgets/VisualNavbar.cpp index 472568d6..1501dc3c 100644 --- a/src/widgets/VisualNavbar.cpp +++ b/src/widgets/VisualNavbar.cpp @@ -16,12 +16,12 @@ #include #include -VisualNavbar::VisualNavbar(MainWindow *main, QWidget *parent) : - QToolBar(main), - graphicsView(new QGraphicsView), - seekGraphicsItem(nullptr), - PCGraphicsItem(nullptr), - main(main) +VisualNavbar::VisualNavbar(MainWindow *main, QWidget *parent) + : QToolBar(main), + graphicsView(new QGraphicsView), + seekGraphicsItem(nullptr), + PCGraphicsItem(nullptr), + main(main) { Q_UNUSED(parent); @@ -31,7 +31,8 @@ VisualNavbar::VisualNavbar(MainWindow *main, QWidget *parent) : setContentsMargins(0, 0, 0, 0); // If line below is used, with the dark theme the paintEvent is not called // and the result is wrong. Something to do with overwriting the style sheet :/ - //setStyleSheet("QToolBar { border: 0px; border-bottom: 0px; border-top: 0px; border-width: 0px;}"); + // setStyleSheet("QToolBar { border: 0px; border-bottom: 0px; border-top: 0px; border-width: + // 0px;}"); /* QComboBox *addsCombo = new QComboBox(); @@ -40,7 +41,7 @@ VisualNavbar::VisualNavbar(MainWindow *main, QWidget *parent) : addsCombo->addItem("Marks"); */ addWidget(this->graphicsView); - //addWidget(addsCombo); + // addWidget(addsCombo); connect(Core(), &CutterCore::seekChanged, this, &VisualNavbar::on_seekChanged); connect(Core(), &CutterCore::registersChanged, this, &VisualNavbar::drawPCCursor); @@ -135,14 +136,17 @@ void VisualNavbar::updateGraphicsScene() RVA beginAddr = stats.from; double widthPerByte = (double)w / (double)totalSize; - auto xFromAddr = [widthPerByte, beginAddr] (RVA addr) -> double { + auto xFromAddr = [widthPerByte, beginAddr](RVA addr) -> double { return (addr - beginAddr) * widthPerByte; }; std::array(DataType::Count)> dataTypeBrushes; - dataTypeBrushes[static_cast(DataType::Code)] = QBrush(Config()->getColor("gui.navbar.code")); - dataTypeBrushes[static_cast(DataType::String)] = QBrush(Config()->getColor("gui.navbar.str")); - dataTypeBrushes[static_cast(DataType::Symbol)] = QBrush(Config()->getColor("gui.navbar.sym")); + dataTypeBrushes[static_cast(DataType::Code)] = + QBrush(Config()->getColor("gui.navbar.code")); + dataTypeBrushes[static_cast(DataType::String)] = + QBrush(Config()->getColor("gui.navbar.str")); + dataTypeBrushes[static_cast(DataType::Symbol)] = + QBrush(Config()->getColor("gui.navbar.sym")); DataType lastDataType = DataType::Empty; QGraphicsRectItem *dataItem = nullptr; @@ -218,7 +222,8 @@ void VisualNavbar::drawCursor(RVA addr, QColor color, QGraphicsRectItem *&graphi void VisualNavbar::drawPCCursor() { - drawCursor(Core()->getProgramCounterValue(), Config()->getColor("gui.navbar.pc"), PCGraphicsItem); + drawCursor(Core()->getProgramCounterValue(), Config()->getColor("gui.navbar.pc"), + PCGraphicsItem); } void VisualNavbar::drawSeekCursor() @@ -268,7 +273,8 @@ double VisualNavbar::addressToLocalX(RVA address) { for (const XToAddress &x2a : xToAddress) { if ((x2a.address_from <= address) && (address < x2a.address_to)) { - double offset = (double)(address - x2a.address_from) / (double)(x2a.address_to - x2a.address_from); + double offset = (double)(address - x2a.address_from) + / (double)(x2a.address_to - x2a.address_from); double size = x2a.x_end - x2a.x_start; return x2a.x_start + (offset * size); } diff --git a/src/widgets/VisualNavbar.h b/src/widgets/VisualNavbar.h index e4666d68..195c23a1 100644 --- a/src/widgets/VisualNavbar.h +++ b/src/widgets/VisualNavbar.h @@ -13,7 +13,8 @@ class VisualNavbar : public QToolBar { Q_OBJECT - struct XToAddress { + struct XToAddress + { double x_start; double x_end; RVA address_from; @@ -36,15 +37,15 @@ private slots: void on_seekChanged(RVA addr); private: - QGraphicsView *graphicsView; - QGraphicsScene *graphicsScene; + QGraphicsView *graphicsView; + QGraphicsScene *graphicsScene; QGraphicsRectItem *seekGraphicsItem; QGraphicsRectItem *PCGraphicsItem; - MainWindow *main; + MainWindow *main; - BlockStatistics stats; - unsigned int statsWidth = 0; - unsigned int previousWidth = 0; + BlockStatistics stats; + unsigned int statsWidth = 0; + unsigned int previousWidth = 0; QList xToAddress; diff --git a/src/widgets/WidgetShortcuts.h b/src/widgets/WidgetShortcuts.h index b85d981a..e68bd6cb 100644 --- a/src/widgets/WidgetShortcuts.h +++ b/src/widgets/WidgetShortcuts.h @@ -2,12 +2,9 @@ #define WIDGETSHORTCUTS_H static const QHash widgetShortcuts = { - { "StringsWidget", Qt::SHIFT + Qt::Key_F12 }, - { "GraphWidget", Qt::SHIFT + Qt::Key_G }, - { "ImportsWidget", Qt::SHIFT + Qt::Key_I }, - { "ExportsWidget", Qt::SHIFT + Qt::Key_E }, - { "ConsoleWidget", Qt::CTRL + Qt::Key_QuoteLeft }, - { "ConsoleWidgetAlternative", Qt::Key_Colon } + { "StringsWidget", Qt::SHIFT + Qt::Key_F12 }, { "GraphWidget", Qt::SHIFT + Qt::Key_G }, + { "ImportsWidget", Qt::SHIFT + Qt::Key_I }, { "ExportsWidget", Qt::SHIFT + Qt::Key_E }, + { "ConsoleWidget", Qt::CTRL + Qt::Key_QuoteLeft }, { "ConsoleWidgetAlternative", Qt::Key_Colon } }; #endif diff --git a/src/widgets/ZignaturesWidget.cpp b/src/widgets/ZignaturesWidget.cpp index 6bd46449..d9c61760 100644 --- a/src/widgets/ZignaturesWidget.cpp +++ b/src/widgets/ZignaturesWidget.cpp @@ -4,8 +4,7 @@ #include "common/Helpers.h" ZignaturesModel::ZignaturesModel(QList *zignatures, QObject *parent) - : QAbstractListModel(parent), - zignatures(zignatures) + : QAbstractListModel(parent), zignatures(zignatures) { } @@ -43,11 +42,10 @@ QVariant ZignaturesModel::data(const QModelIndex &index, int role) const return QVariant::fromValue(zignature); case Qt::ToolTipRole: { - QString tmp = QString("Graph:\n\n Cyclomatic complexity: " + RSizeString(zignature.cc) + - "\n Nodes / basicblocks: " + RSizeString(zignature.nbbs) + - "\n Edges: " + RSizeString(zignature.edges) + - "\n Ebbs: " + RSizeString(zignature.ebbs) + - "\n\nRefs:\n"); + QString tmp = QString("Graph:\n\n Cyclomatic complexity: " + RSizeString(zignature.cc) + + "\n Nodes / basicblocks: " + RSizeString(zignature.nbbs) + + "\n Edges: " + RSizeString(zignature.edges) + + "\n Ebbs: " + RSizeString(zignature.ebbs) + "\n\nRefs:\n"); for (const QString &ref : zignature.refs) { tmp.append("\n " + ref); } @@ -87,17 +85,17 @@ ZignaturesProxyModel::ZignaturesProxyModel(ZignaturesModel *sourceModel, QObject bool ZignaturesProxyModel::filterAcceptsRow(int row, const QModelIndex &parent) const { QModelIndex index = sourceModel()->index(row, 0, parent); - ZignatureDescription item = index.data( - ZignaturesModel::ZignatureDescriptionRole).value(); + ZignatureDescription item = + index.data(ZignaturesModel::ZignatureDescriptionRole).value(); return item.name.contains(filterRegExp()); } bool ZignaturesProxyModel::lessThan(const QModelIndex &left, const QModelIndex &right) const { - ZignatureDescription leftZignature = left.data( - ZignaturesModel::ZignatureDescriptionRole).value(); - ZignatureDescription rightZignature = right.data( - ZignaturesModel::ZignatureDescriptionRole).value(); + ZignatureDescription leftZignature = + left.data(ZignaturesModel::ZignatureDescriptionRole).value(); + ZignatureDescription rightZignature = + right.data(ZignaturesModel::ZignatureDescriptionRole).value(); switch (left.column()) { case ZignaturesModel::OffsetColumn: @@ -113,9 +111,8 @@ bool ZignaturesProxyModel::lessThan(const QModelIndex &left, const QModelIndex & return leftZignature.offset < rightZignature.offset; } -ZignaturesWidget::ZignaturesWidget(MainWindow *main) : - CutterDockWidget(main), - ui(new Ui::ZignaturesWidget) +ZignaturesWidget::ZignaturesWidget(MainWindow *main) + : CutterDockWidget(main), ui(new Ui::ZignaturesWidget) { ui->setupUi(this); @@ -149,7 +146,7 @@ void ZignaturesWidget::setScrollMode() void ZignaturesWidget::on_zignaturesTreeView_doubleClicked(const QModelIndex &index) { - ZignatureDescription item = index.data( - ZignaturesModel::ZignatureDescriptionRole).value(); + ZignatureDescription item = + index.data(ZignaturesModel::ZignatureDescriptionRole).value(); Core()->seekAndShow(item.offset); } diff --git a/src/widgets/ZignaturesWidget.h b/src/widgets/ZignaturesWidget.h index 46e75836..88a6d945 100644 --- a/src/widgets/ZignaturesWidget.h +++ b/src/widgets/ZignaturesWidget.h @@ -40,8 +40,6 @@ private: QList *zignatures; }; - - class ZignaturesProxyModel : public QSortFilterProxyModel { Q_OBJECT @@ -54,8 +52,6 @@ protected: bool lessThan(const QModelIndex &left, const QModelIndex &right) const override; }; - - class ZignaturesWidget : public CutterDockWidget { Q_OBJECT